Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Okay, I am wanting to basically connect my windows form application in C# to my database, what I want it to do is display a random word from the database into the label of my form. When I say display a random word I mean display a random word from the 20 words in a table of my database. I was wondering how would you do this? I really dont want the answer as I want to learn, but could you explain how would I do this?
Thanks in advance:)
I am wanting to connect the database using Access rather than the framework provided by .NET
First of all I would like to suggest to use google first Beginners guide to connect SQL with C# then I would like you to post question regarding to one topic for instance - Connect SQL with C#. And the part with picking random word should be another solo question.
Anyway I hope this will work for you, but please, keep in mind that we are not here to code for you without any coding effort and your code.
My code:
List<string> wordList = new List<string>();
string connection = "YourConnectionString";
OleDbConnection con = new OleDbConnection(connection);
string query = "SELECT * FROM yourTable WHERE ID=#param"; // add as many conditions as you need
OleDbCommand comm = new OleDbCommand(query, con);
comm.Parameters.AddWithValue("#param", textBox1.Text); //example of parameter
con.Open();
OleDbDataReader rdr = comm.ExecuteReader();
while (rdr.Read()) //this will loop through all rows with given conditions.
{
wordList.Add(rdr.GetString(rdr.GetOrdinal("YourSQLColumn")).Trim());
}
con.Close();
Random rnd = new Random();
int randomint = rnd.Next(1, 20); // generates a random number between 1 and 20
label1.Text = wordList[randomint].ToString();
Here's a sample to get you started
public static void Main()
{
string connectionString = "data source=.\\SQLEXPRESS;Integrated Security=SSPI;database=InsertDatabaseNameHere; connection timeout=30";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand("select ColumnName from TableName", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetValue(0));
}
connection.Close();
}
Just set up a SQLDataReader and convert to a list...you just have a one-dimensional list of strings. You'll be looping through the results and adding them to a list. (There's probably a more elegant way to do this, but you've only got 20 strings, not 20,000, so I don't think you need to get crazy with this)
Here's another SO question to get you started...this answer is probably what you need.
You just set your Datareader up against Access (there's a bazillion hits on doing this), convert it to a list, and off you go...
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source = LAPTOP-ULT25NKH; database = college;integrated security = True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from teacher where tID = " + textBox1.Text + "";
DataSet DS = new DataSet();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
}
but I get this exception:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '='."
Ensure you are properly santizing inputs and using prepared statements; to start down the line for you, try:
cmd.CommandText = "SELECT * FROM teacher WHERE tID = #tID;"
SqlParameter idParam = new SqlParameter("#tID", SqlDbType.NVarChar , 0);
idParam.Value = textBox1.Text;
cmd.Parameters.Add(idParam);
cmd.Prepare();
There are lot of issues in your existing code, I’m mentioning few points brlow.
Please move the connection string to some config file, it’s easy to maintain there.
When you have DataAdapter you don’t need to explicitly open the connection, it does that for you internally.
Please avoid * in select query, mention the columns with alias and use parameterized query to pass the parameters. Or your can write stored procedure and call it. So that I if I’m future you need to modify query, there will be no code change.
If you need to open the connection, please close it or your can use using.
You can add breakpoint and see the value of your query and if you copy this query value and run in sql server directly . This is one way to find the error in the query.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm using below code but, it's giving me an error.
private void ma2()
{
try
{
string query = "select k7 from kholy1";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
con.Open();
SqlDataReader drd = cmd.ExecuteReader();
while (drd.Read())
{
comboBox5.Items.Add(drd.GetValue(0).ToString());
}
drd.Close();
}
catch
{
MessageBox.Show("Error ");
}
}
I'm getting an error while displaying the form!
You just simply use combo box tasks and check use Data Bound Items that's how you are able to connect it to sql database. Value member use to store it's value in database and Display Member use to Display value in front end.
You can use selected value using combobox1.SelectedValue.
Reference- Binding WPF ComboBox to a Custom List
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I still new to C# and just have 3 months plus of learning process. I would like to seeking advice on how to extract data value from my DataTable I have create for validation checking.
private void checker
{
string sqlSelect2 = "SELECT a.AccNo, a.CompanyName , a.CreditLimit, FROM Debtor a JOIN";
}
which i have named TableCehecker, i do not need to put it to gridview, just for checking purposes.
In the private void process how can I extract dataTable TableCehecker and the value?
Thank you,
Brian
You need to follow the Docs from MSDN:
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
DataTable dt = new DataTable();
dt.Load(reader);
sqlConnection1.Close();
You can then check whatever you want of data inside the DataTable either by querying or by looping through the rows and checking the column values.
Based on your comments, to extract values from single row:
DataRow drow = dt.Rows[0];
string value = drow.Field<string>("CompanyName");
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am creating a form for alerting the user that the stock for this item in the database is getting the limit or passed right through the limit.
this is my code for checking the quantity of a certain stock
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select * from tbl_BloodChemistry where Glucose = "+123+" ";
reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Critical!");
}
conn.Close();
It's not actually the answer, but you have no reason to retrieve all data to collect count of rows. Use SQL COUNT and ExecuteScalar() for this.
Also, it's important to use command Parameters to your query. Don't ever build a query in your way! The input variable, Glucose, is typically retrieved from a TextBox control on either a Windows form or a Web Page. Anything placed into that TextBox control will be put into inputCity and added to your SQL string. This situation invites a hacker to replace that string with something malicious. In the worst case, you could give full control of your computer away.
Instead of dynamically building a string, as shown in the bad example above, use parameters. Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure.
Using parameterized queries is a three step process:
Construct the SqlCommand command string with parameters.
Declare a SqlParameter object, assigning values as appropriate.
Assign the SqlParameter object to the SqlCommand object's Parameters property.
var glucoseFilterValue = "123";
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select count(*) from tbl_BloodChemistry where Glucose = #Glucose";
cmd.Parameters.AddWithValue("#Glucose", glucoseFilterValue);
var count = (int) cmd.ExecuteScalar();
if (count == 1)
{
MessageBox.Show("Critical!");
}
conn.Close();
Then you'll make your code more clean and prevent extra loading to your communication channel.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This method below goes into a table and deletes all of the table. But in the datatable "table" below in the first column there are dates which i would like to be deleted from the database. how would i go about doing this
Datatable table = new DataTable()
string sqlConnectionString =
"Server = 100.720.8.196; Database = testDat; User Id = sa; Password = ";
// Copy the DataTable to SQL Server
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
string deleteSting =
"delete from dbo.testTable where clientId=1212";
conn.Open();
using (SqlCommand cmd = new SqlCommand(deleteSting, conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
I'm just guessing here, you probably mean to make the date column empty. If that's the case then you use UPDATE, like:
string updateString =
"UPDATE dbo.testTable SET datecol = #datecol where clientId=#clientID";
conn.Open();
using (SqlCommand cmd = new SqlCommand(updateString, conn))
{
cmd.Parameters.Add("#datecol", SqlDbType.Date).Value = DbNull.Value;
cmd.Parameters.Add("#clientID", SqlDbType.Int).Value = 1212;
cmd.ExecuteNonQuery();
}
conn.Close();
Well, there are a few options. You could loop through your table and create a string containing your dates in a comma separated list. With that, you can create a SQL Statement like delete from table where dateCol in (date1, date2, date3, etc...)
Or you could just loop through your data table, and do one delete per loop iteration. Either way will work.
However you decide to proceed, make sure to use parameters instead of string concatenation to prevent issues like SQL Injections:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx