Sql Exception was unhandled c# log in - c#

SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename= C: \Users\Marco\Documents\Visual Studio 2015\Projects\HungryGorilla\HungryGorilla\User.mdf;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from [Login] where Username='" + unametxt.Text + "'and Password = '" + pwordtxt.Text + "'",con);
DataTable dt = new DataTable();
sda.Fill(dt);
the SDA has error = SqlException was unhandled

Related

delete and update the selected row

executenonquery is my problem, this code works on other button in different datagridview
here's my code at delete button
private void button4_Click_2(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=XXYZZ\SQLEXPRESS;Initial Catalog=rick_inventiory;Integrated Security=True");
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete from tbl_Orders where CustomersID2 = '" + dataGridView5.SelectedRows[0].Cells[0].Value.ToString() + "'";
con.Open();
cmd.Parameters.AddWithValue("#CustomerID2", txtCustomerID2.Text);
cmd.ExecuteNonQuery();
con.Close();
disp_data();
MessageBox.Show("Deleted Successfully");
}
the update code still execute sa code but did not update it
and heres my code for Update button
SqlConnection con = new SqlConnection(#"Data Source=XXYZZ\SQLEXPRESS;Initial Catalog=rick_inventiory;Integrated Security=True");
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Update tbl_Products SET ProductName='" + txtProName.Text +
"',Stocks='" + txtStocks.Text + "',Price='" + txtPrice.Text + "',Description='" +
txtDesc.Text + "',CategoryName='" + txtCat.Text + "' where ProductID ='" + txtProID.Text + "';";
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter("Select * from tbl_Products", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
MessageBox.Show("Successfuly Updated");
con.close();
In update there is a syntax problem remove inner side semi colon of update query
While in delete you want to change the line
from
cmd.Parameters.AddWithValue("#CustomerID2", txtCustomerID2.Text);
to
cmd.Parameters.AddWithValue("#CustomerID2", '" + dataGridView5.SelectedRows[0].Cells[0].Value.ToString() + "');

how to update data without change existing data c# ms access

Hi guys when I want to update without changing old data I get this error
Syntax error (missing operator) in query expression 'data.[Phone Number]+ ' ' +0770444 +'.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE data SET data.[Phone Number] = data.[Phone Number]+ ' ' +"+textBox23.Text+" + WHERE data.([ID]) = " + textBox15.Text + " ";
cmd.Connection = con;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt;
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
MessageBox.Show("Data Updated Successfully");
con.Close();
Start using Command Parameters and you will avoid problems like this:
cmd.CommandText = #"UPDATE data SET [Phone Number] = [Phone Number] + ' ' + #NewPhoneNumber WHERE ID = #ID ";
cmd.Parameters.AddWithValue("#ID", textBox15.Text);
cmd.Parameters.AddWithValue("#NewPhoneNumber", textBox23.Text);
cmd.Connection = con;
Also this will protect you from Sql Injection. Be aware you should provide proper naming of your controls(textboxes), this names means nothing for other programmers. Write your columns together PhoneNumber it is annoying to escape them all the time, you are creating more work for yourself for no reason.
Other points wrap your OleDbConnection and OleDbDataAdapter in using blocks
using(OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb"))
{
con.Open();
//... stuff
DataTable dt;
using(OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
//stuff relate to db adapter
}
}
Using is representing try/catch/finally with calling Dispose() in finally block. This will protect if your code have an exception your connection will be closed. In your current format this is not happening. OleDbDataAdapter is using unmanaged resources so it should be Dispose() too.
Your command seems to be wrong it should be
cmd.CommandText = "UPDATE data SET data.[Phone Number] = " + "'" + data.[Phone Number] + textBox23.Text + "' WHERE data.([ID]) = " + textBox15.Text;
Whereas it is always recommended that we should use the Parameterized Query instead of string concat.
thanks guys I resolved it by this
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE data SET [Phone Number] = [Phone Number]+\n'" + textBox3.Text + "' WHERE ID = " + textBox15.Text + " ";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("New Number Inserted Successfully to ID " + textBox15.Text);
con.Open();

Populating SQL Server Datatable

My program will not update my SQL Server database after executing. When I run my program my DataGridView updates when I insert my information, but it will not update itself in the dataTable.
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES('" + idTextBox.Text + "','" + nameTextBox.Text + "','" + ageTextBox.Text + "')";
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
this.dataTableTableAdapter.Fill(this.employeeDataSet1.dataTable);
conn.Close();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataTable data = new DataTable();
conn.Open();
adapt.Update(data);
conn.Close();
dataTableDataGridView.DataSource = data;
}
If you created your DataGridView using the designer which added a dataset, bindingsource, and tableadapter, then your DataGridView should be configured correctly out of the box. Try commented out these lines:
//SqlDataAdapter adapt = new SqlDataAdapter(cmd);
//DataTable data = new DataTable();
//conn.Open();
//adapt.Update(data);
//conn.Close();
//dataGridView1.DataSource = data;
I replicated your button_click code and it works locally for me using Sql Express.
Based on your comment i assume the cause is the missing conversion. Using Int32.TryParse you can convert the string to int. Be aware that the ' have to go as well
int id, age;
bool idIsInt = false, ageIsInt = false;
idIsInt = Int32.TryParse(idTextBox.Text, out id);
ageIsInt = Int32.TryParse(ageTextBox.Text, out age);
if(idIsInt && ageIsInt)
{
string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES("
+ id + ",'" + nameTextBox.Text + "',"
+ age + ")";
SqlConnection conn =
new SqlConnection(#"Data Source(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf
;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
}

Select from two tables by using a textbox value

I have two tables and I want to search into them by using a TextBox and this is my code but wrong hope to help me
string constring = "Data Source =.; initial Catalog = business; Integrated Security=SSPI;";
SqlConnection CN = new SqlConnection(constring);
DataTable dt = new DataTable();
if (txtID.Text.Trim() != "")
{
SqlDataAdapter sda = new SqlDataAdapter("select tab1.ID ,tab1.DATMOSTAND ,tab1.MONY ,tab2.BYAN ,tab2.MONY from MAL_ERTEBAT,tab2 where tab1.ID = tab2.EID = '" + txtID.Text + "'", CN);
sda.Fill(dt);
}
dataGridView1.DataSource = dt;
where tab1.ID = tab2.EID = '" + txtID.Text + "'" this is the error part the message is "in correct syntax near ="
Hope you are missing the alias name:
Replace the above SqlDataAdapter with:
SqlDataAdapter sda = new SqlDataAdapter("select tab1.ID ,tab1.DATMOSTAND ,tab1.MONY ,tab2.BYAN ,tab2.MONY from MAL_ERTEBAT tab1,tab2 where tab1.ID = tab2.EID = '" + txtID.Text + "'", CN);

how to get particular record by using where condition in webservice?

I want to return a particular record from the webservice. Still what i have successfully done is, got all the records by the following code:
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
[WebMethod]
public DataSet Getmember()
{
con = new SqlConnection(#"Data Source=SQLDOTNET\MSSQLSERVER2008;Initial Catalog=doctor;Persist Security Info=True;User ID=sa;pwd=test123#;");
adap = new SqlDataAdapter("select * from tblusers", con);
ds = new DataSet();
adap.Fill(ds, "tblusers");
return ds;
}
Now i want to get a particular record by Emailid for that i have tried the following code:
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
[WebMethod]
public DataSet Getmember(String Emailid)
{
Emailid = "test#test.com";
con = new SqlConnection(#"Data Source=SQLDOTNET\MSSQLSERVER2008;Initial Catalog=doctor;Persist Security Info=True;User ID=sa;pwd=test123#;");
adap = new SqlDataAdapter("select * from tblusers where EmailAddress=" + Emailid, con);
ds = new DataSet();
adap.Fill(ds, "tblusers");
return ds;
}
But this code throwing the following error:
System.Data.SqlClient.SqlException: Invalid column name 'test#test.com'.
Please help me..
You need to enclose string literals in single quotes in SQL:
"select * from tblusers where EmailAddress = '" + Emailid + "'"
But this leaves you open to SQL injection attacks and is not recommended. (Examine what would happen if Emailid were set to "' OR 1=1 OR ''='".)
You should specify Emailid as a parameter value instead:
var cmd = new SqlCommand("select * from tblusers where EmailAddress = ?");
cmd.Parameters.Add(Emailid);
adap = new SqlDataAdapter(cmd, con);
change the
Emailid = "test#test.com";
to
Emailid = "'test#test.com'";
Note the extra single quotes arount emailid
Dont know if this would help cause I havent use C # for some time
I think your error goes on this part
select * from tblusers where EmailAddress=" + Emailid
Try changing it to
"select * from tblusers where EmailAddress='" + Emailid + "'"
At first you should use SQL parameters... not the plain SQL queries so better check SQL Parameters
adap = new SqlDataAdapter("select * from tblusers where EmailAddress=" + Emailid, con);
should be changed to
adap = new SqlDataAdapter("select * from tblusers where EmailAddress='" + Emailid + "'", con);
You miss to have "'" in you query .. Better you look at the statement syntax...

Categories