Error An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code. How to fix it?
Image: http://i.stack.imgur.com/7Sibc.png
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand sc = new SqlCommand("select Title from TongHopDB", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Title", typeof(string));
dt.Load(reader);
cboxDB.ValueMember = "Title";
cboxDB.DisplayMember = "Title";
cboxDB.DataSource = dt;
conn.Close();
}
private void cboxDB_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "Select Title, Post from TongHopDB where Title = " + cboxDB.SelectedValue.ToString(); // câu query có thể khác với kiểu dữ liệu trong database của bạn
SqlConnection conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader sdr = cmd.ExecuteReader();
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
sdr.Close();
sdr.Dispose();
conn.Close();
conn.Dispose();
}
string sql = "Select Title, Post from TongHopDB where Title = '" + cboxDB.SelectedValue.ToString()+"'";
However I strongly suggest to use parameters:
string sql = "Select Title, Post from TongHopDB where Title = #Title";
cmd.Paramaters.Add( "#Title",cboxDB.SelectedValue.ToString());
I strongly suspect your Title is character typed, that's why it needs to used with single quotes as;
where Title = '" + cboxDB.SelectedValue.ToString() + "'";
But don't use this way.
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataReader objects automatically instead of calling Close or Dispose methods manually.
using(var conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7"))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "Select Title, Post from TongHopDB where Title = #title";
cmd.Parameters.Add("#title", SqlDbType.NVarChar).Value = cboxDB.SelectedValue.ToString();
// I assumed your column type is nvarchar.
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
if(dr.Read())
{
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
}
}
}
cboxDB.SelectedValue is Apple according to the error shown in your screen shot. Your SQL statement is saying in plain English:
Select Title(column) and Post(column) from TongHopDB(table) where Title(column) equals Apple(column)
Apple is not a valid column!
While it would work to simply add single quotes around the value of cboxDB, you should use parameters instead of concatenating a string. http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/
Related
In the code below, i just want to fill my textbox based on the selected combo box changed. but i get the following error.
'Conversion failed when converting the varchar value
'System.Data.DataRowViewConvert.ToString()' to data type int.'
i'd appreciate it if you help me.
SqlConnection objConnection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\UniversityDataBase.mdf;Integrated Security=True");
private void comboBox1_Click(object sender, EventArgs e)
{
string query = "SELECT *FROM TutorTable";
SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
DataTable dt = new DataTable();
SDA.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Tid";
objConnection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sqlQuery = "SELECT *FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'";
SqlCommand objCommand = new SqlCommand(sqlQuery, objConnection);
objConnection.Open();
objCommand.ExecuteNonQuery();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string Tname = (string)dr["Tname"].ToString();
textBox1.Text = Tname;
}
}
Why are you using the Convert.ToString() in this piece of code:
"SELECT * FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'"
I think the correct way wolud be:
"SELECT * FROM TutorTable where Tid = '"+comboBox1.Text+ "'"
But consider using a store procedure to prevent sql injection or using an ORM.
I think that comboBox1.Text is already returning a string value. So if that, it is not necessary to put the Convert.ToString(comboBox.Text), just put comboBox1.Text
According to documentation, the Text property is a string
https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.text(v=vs.110).aspx
I found the Solution as follows:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\UniversityDataBase.mdf;Integrated Security=True");
string sqlQuery = "SELECT *FROM TutorTable WHERE Tid = '" + comboBox1.Text + "'";
SqlCommand objCommand = new SqlCommand(sqlQuery, con);
con.Open();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string name = (string)dr["Tname"].ToString();
textBox1.Text = name;
}
}
You have got the answer already but few more things should be taken care of
Your code
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sqlQuery = "SELECT *FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'";
SqlCommand objCommand = new SqlCommand(sqlQuery, objConnection);
objConnection.Open();
objCommand.ExecuteNonQuery();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string Tname = (string)dr["Tname"].ToString();
textBox1.Text = Tname;
}
}
Things to notice:
1) Use varabled instead of manipulating sql
e.g. SELECT *FROM TutorTable where Tid = #id and pass id into sqlCommand object
2) You dont need to call ExecuteNonQuery before SqlDataReader
3) you need to use if(dr.Read()) instead of while
4) You can directly assign value textbox.
e.g. texBox1.Text = dr["Tname"].ToString();
5) Close the objConnection
If I enter a value(already entered in DB) and click a button(Retrieve) in my windows form, I have to retrieve date and time to my datetimepicker1 from SQL(already entered values).
Please correct my code.
This is my code.
private void button9_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=NIFAL;Initial Catalog=LaundrySystem;Integrated Security=True;");
con.Open();
str = "select * from LaundrySystemTable where laundID='" + textBox1.Text.Trim() + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
string temp1 = reader["entryDate"].ToString();
DateTime dt1 = DateTime.Parse(temp1);
dateTimePicker1.Value = dt1.ToString("MM:dd:yyyy");
reader.Close();
con.Close();
}
}
NEVER use such an SQL that is open to SQL inkjection attacks, use parameters instead:
using (SqlConnection con = new SqlConnection("Data Source=NIFAL;Initial Catalog=LaundrySystem;Integrated Security=True;"))
{
string sql = "select entryDate from LaundrySystemTable where laundID=#id";
var cmd = new SqlCommand( sql, con );
cmd.Parameters.AddWithValue( "#id", textBox1.Text.Trim() ); // if its type is not string, then do the conversion here
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
dateTimePicker1.Value = (DateTime?)reader["entryDate"];
}
con.Close();
}
Im trying to add items in the comboBox (cmbInstructor) namely the last names (instructorLN) however, my code does not seem to work. Any ideas on where I went wrong?
private void cmbInstructor_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(mycon);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM instructor WHERE instructorType ='" + labelClass.Text + "'", conn);
string instructorLN = "";
conn.Open();
MySqlDataReader myReader = null;
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
instructorLN = myReader["instructorLN"].ToString();
}
cmbInstructor.Items.Add(instructorLN);
}
As far as I can see, you are adding only last value that your SELECT returns.
Move your
cmbInstructor.Items.Add(instructorLN);
line into to the while statement as;
while (myReader.Read())
{
cmbInstructor.Items.Add(myReader["instructorLN"].ToString());
}
By the way, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connection and command and reader automatically.
using(var conn = new MySqlConnection(mycon))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM instructor WHERE instructorType = #type";
cmd.Parameters.Add("#type", labelClass.Text);
conn.Open();
using(var myReader = cmd.ExecuteReader())
{
while (myReader.Read())
{
cmbInstructor.Items.Add(myReader["instructorLN"].ToString());
}
}
}
private void fillProduct() {
SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
string query = "Select prodID from product";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) {
cmbPCode.DataSource = dt;
cmbPCode.DisplayMember = "prodID";
cmbPCode.ValueMember = "prodID";
}
private void cmbPCode_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
con.Open();
string query = "Select * from product where prodID = '"+cmbPCode.Text+"'".ToString();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
tbdc.Text = dr["prodDescription"].ToString();
}
}
i am having trouble with getting my items from the database according to the selected index i get this error
Conversion failed when converting the varchar value
'System.Data.DataRowView' to data type int
can someone please help me how to convert SqlDataReader to String. because i notice that when i retrieve a column with varchar/string datatype i am not having this kind error but if i retrieve a column with int datatype i get this error.
Replace This:
string query = "Select * from product where prodID = '"+cmbPCode.Text+
"'".ToString();
With This:
string query = "Select * from product where prodID = "+cmbPCode.Text;
Suggestion: Your query is open to SQL Injection i would suggest you to use parameterised queries to avoid them.
Using Parameterised Queries:
string query = "Select * from product where prodID = #ID";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID",cmbPCode.Text);
I want to retrieve the resulting value of a select statement into a string variable. Like this:
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
cmd1.ExecuteNonQuery();
I want to place the selected treatment value into a string variable. How can I do this?
Use ExecuteReader() and not ExecuteNonQuery(). ExecuteNonQuery() returns only the number of rows affected.
try
{
SqlDataReader dr = cmd1.ExecuteReader();
}
catch (SqlException oError)
{
}
while(dr.Read())
{
string treatment = dr[0].ToString();
}
Or better, use a using statement for it.
using(SqlDataReader dr = cmd1.ExecuteReader())
{
while(dr.Read())
{
string treatment = dr[0].ToString();
}
}
But if your SqlCommand returns only 1 column, you can use the ExecuteScalar() method. It returns first column of the first row as follows:-
cmd.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
string str = Convert.ToString(cmd.ExecuteScalar());
Also you can open your code to SQL Injection. Always use parameterized queries. Jeff has a cool blog article called Give me parameterized SQL, or give me death. Please read it carefully. Also read DotNetPerl SqlParameter article. SQL Injection very important when you are working queries.
Execute Scalar: Getting Single Value from the Database method to retrieve a single value (for example, an aggregate value) from a database.
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
if(cmd.ExecuteScalar()==null)
{
var treatment = cmd.ExecuteScalar();
}
Other Way: ExecuteReader()
try
{
cmd1.CommandText ="SELECT treatment FROM appointment WHERE patientid=#patientID";
cmd1.Parameters.AddWithValue("#patientID", this.DropDownList1.SelectedValue);
conn.Open();
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
int PatientID = int.Parse(dr["treatment"]);
}
reader.Close();
((IDisposable)reader).Dispose();//always good idea to do proper cleanup
}
catch (Exception exc)
{
Response.Write(exc.ToString());
}
the answer:
String res = cmd1.ExecuteScalar();
the remark: use parametrized query to prevent sql injection
There is a lot wrong with your example code.
You have inline sql, which opens you up to sql injection in a major way.
You are using ExecuteNonQuery() which means you get no data back.
string sSQL = "SELECT treatment FROM appointment WHERE patientid = #patientId";
OleDbCommand cmd1 = new OleDbCommand(sSQL, GetConnection()); // This may be slight different based on what `GetConnectionReturns`, just put the connection string in the second parameter.
cmd1.Parameters.AddWithValue("#patientId", text);
SqlDataReader reader = cmd1.ExecuteReader();
string returnValue;
while(reader.Read())
{
returnValue = reader[0].ToString();
}
You just need to use the ExecuteScalar method of the command - this will give you the value at the first row and column of the result set.
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
var result = cmd1.ExecuteScalar();
If your SQL statement returns more than one row/column then you can use ExecuteReader().
You need to use OleDbAdapter.
string connection = "your connection";
string query = "SELECT treatment FROM appointment WHERE patientid = " + text;
OleDbConnection conn = new OleDbConnection(connection);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.Fill(dataset);
SqlConnection dbConnect = new SqlConnection("your SQL connection string");
string name = " 'ProjectName' ";
string strPrj = "Select e.type, (e.surname +' '+ e.name) as fulln from dbo.tblEmployees e where id_prj = " + name;
SqlCommand sqlcmd = new SqlCommand(strPrj, dbConnect);
SqlDataAdapter sda = new SqlDataAdapter(strPrj, dbConnect);
ds = new DataSet();
sda.Fill(ds);
dbConnect.Open();
sqlcmd.ExecuteNonQuery();
dbConnect.Close();