string Update = "UPDATE VehicleReport" +
"SET VehicleReg ='"+textBox1.Text+"',CurrentOdometer ='"+textBox5.Text+"',NextService ='"+textBox6.Text+"'" +
"WHERE Vehiclenum ='"+comboBox1.Text+"' ;";
try
{
SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=FleetTrackingDatabase;Integrated Security=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand(Update, conn);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Updated");
conn.Close();
}
catch (System.Exception f)
{
MessageBox.Show(f.Message, "ERROR");
}
At least this is not correct:
string Update = "UPDATE VehicleReport" + "SET ...
you need to add a space between VehicleReport and Set
string Update = "UPDATE VehicleReport " + "SET....
Add spaces
"UPDATE VehicleReport" +
" SET VehicleReg ='"+textBox1.Text+"',CurrentOdometer ='"+textBox5.Text+"',NextService='"+textBox6.Text+"'" +
" WHERE Vehiclenum ='"+comboBox1.Text+"' ;";
There is missing space after table name :
string Update = "UPDATE VehicleReport"
string Update = "UPDATE VehicleReport "
and the same before WHERE
Can you try this,
string Update = "UPDATE VehicleReport SET VehicleReg ='"+textBox1.Text+"',CurrentOdometer ='"+textBox5.Text+"',NextService ='"+textBox6.Text+"'" + " WHERE Vehiclenum ='"+comboBox1.Text+"' ;";
I'm really shocked there are 4 answers but nobody mentioned about parameterized sql and SQL Injection attacks but anyway..
As others mentioned, you need spaces before your SET and WHERE words.
But more more more important is, DON'T USE THIS WAY. When you use string concatenations in your queries, your code will be open for SQL Injection. Instead of this, you should always use parameterizezd queries.
For example;
string Update = "UPDATE VehicleReport SET VehicleReg = #vehiclereg, CurrentOdometer = #current, NextService = #next WHERE Vehiclenum = #vehiclenum;";
SqlCommand cmd = new SqlCommand(Update, conn);
cmd.Parameters.AddWithValue("#vehiclereg", textBox1.Text);
cmd.Parameters.AddWithValue("#current", textBox5.Text);
cmd.Parameters.AddWithValue("#next", textBox6.Text);
cmd.Parameters.AddWithValue("#vehiclenum", comboBox1.Text);
Related
I know plenty of people have these issues, and I've actually tried to implement some of the suggestions to my code, however I'm getting errors that just don't make sense to me. This is my first time implementing database calls to my code. Can someone please tell me what I'm doing wrong? The following error pops up: ERROR: Invalid object name 'Main'. This is actually triggered by my exception so at least something is working. Otherwise, I don't know what the issue is. On the DB end, I have (username VARCHAR, email VARCHAR and number NCHAR) Please see the code below
static string path = Path.GetFullPath(Environment.CurrentDirectory);
static string databaseName = "u_DB.mdf";
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + #"\" + databaseName + "; Integrated Security=True;";
private void button1_Click(object sender, EventArgs e)
{
// string query = "INSERT INTO UserInfo '" + textBox1.Text + "' and password = '" + textBox2.Text + "'";
string query = "insert into Main ([username], [email], [number]) values(#username,#email,#number)";
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = textBox3.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.AddWithValue("#number", SqlDbType.VarChar).Value = textBox1.Text;
int rowsAdded = cmd.ExecuteNonQuery();
if (rowsAdded > 0)
MessageBox.Show("Added to Database");
else
MessageBox.Show("Nothing was added");
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message);
}
con.Close();
}
}
Firstly, as Chetan assumed, do you have a main table?
The syntax of the query you are using is :
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Furthermore,
AddWithValue(string parameterName, object value (<== The actual value to insert!));
in your case
AddWithValue("#number", textBox1.Text);
is enough.
i have a button that when clicked inserts data from textbox and combobox fields into database tables, but every time i insert it gives me "Invalid attempt to call read when reader is closed". How can i get rid of this error. And tips on optimising the code are welcome, because i know im a total noob. thanks
private void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query1 = "insert into location(Storage, Shelf, columns, rows) values(" + txtWarehouse.Text + ", " + txtShelf.Text + ", " + txtColumn.Text + ", " + txtRow.Text + ")";
SqlCommand sqlCmd = new SqlCommand(Query1, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
sqlCon.Close();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query3 = "SELECT LOCATION_ID FROM LOCATION WHERE storage='" + txtWarehouse.Text + "' AND shelf='" + txtShelf.Text + "' AND columns='"
+ txtColumn.Text + "' AND rows='" + txtRow.Text + "'";
SqlCommand sqlCmd1 = new SqlCommand(Query3, sqlCon);
SqlDataReader dr = sqlCmd1.ExecuteReader(); ;
while (dr.Read())
{
string LocationId = dr[0].ToString();
dr.Close();
string Query2 = "insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID) values ('" + txtSku.Text + "','" + txtNimetus.Text + "', '"
+ txtMin.Text + "', '" + txtMax.Text + "', '" + txtQuan.Text + "', '" + LocationId + "', '" + (cbCat.SelectedIndex+1) + "', '" + (cbMail.SelectedIndex+1) + "')";
SqlCommand sqlCmd = new SqlCommand(Query2, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
}
sqlCon.Close();
}
catch (Exception ed)
{
MessageBox.Show(ed.Message);
}
}
Let's try to make some adjustments to your code.
First thing to consider is to use a parameterized query and not a
string concatenation when you build an sql command. This is mandatory
to avoid parsing errors and Sql Injections
Second, you should encapsulate the disposable objects in a using statement
to be sure they receive the proper disposal when you have finished to
use them.
Third, you can get the LOCATION_ID from your table without running a
separate query simply adding SELECT SCOPE_IDENTITY() as second batch to your first command. (This works only if you have declared the LOCATION_ID field in the first table as an IDENTITY column)
Fourth, you put everything in a transaction to avoid problems in case
some of the code fails unexpectedly
So:
SqlTransaction tr = null;
try
{
string cmdText = #"insert into location(Storage, Shelf, columns, rows)
values(#storage,#shelf,#columns,#rows);
select scope_identity()";
using(SqlConnection sqlCon = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, sqlCon))
{
sqlCon.Open();
using( tr = sqlCon.BeginTransaction())
{
// Prepare all the parameters required by the command
cmd.Parameters.Add("#storage", SqlDbType.Int).Value = Convert.ToInt32(txtWarehouse.Text);
cmd.Parameters.Add("#shelf", SqlDbType.Int).Value = Convert.ToInt32(txtShelf.Text);
cmd.Parameters.Add("#columns", SqlDbType.Int).Value = Convert.ToInt32(txtColumn.Text );
cmd.Parameters.Add("#rows", SqlDbType.Int).Value = Convert.ToInt32(txtRow.Text);
// Execute the command and get back the result of SCOPE_IDENTITY
int newLocation = Convert.ToInt32(cmd.ExecuteScalar());
// Set the second command text
cmdText = #"insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID)
values (#sku, #nimetus,#min,#max,#qty,#locid,#catid,#ordid)";
// Build a new command with the second text
using(SqlCommand cmd1 = new SqlCommand(cmdText, sqlCon))
{
// Inform the new command we are inside a transaction
cmd1.Transaction = tr;
// Add all the required parameters for the second command
cmd1.Parameters.Add("#sku", SqlDbType.NVarChar).Value = txtSku.Text;
cmd1.Parameters.Add("#nimetus",SqlDbType.NVarChar).Value = txtNimetus.Text;
cmd1.Parameters.Add("#locid", SqlDbType.Int).Value = newLocation;
.... and so on for the other parameters required
cmd1.ExecuteNonQuery();
// If we reach this point the everything is allright and
// we can commit the two inserts together
tr.Commit();
}
}
}
}
catch (Exception er)
{
// In case of exceptions do not insert anything...
if(tr != null)
tr.Rollback();
MessageBox.Show(er.Message);
}
Notice that in the first command I use parameters of type SqlDbType.Int because you haven't used single quotes around your text. This should be verified against the real data type of your table columns and adjusted to match the type. This is true as well for the second command where you put everything as text albeit some of those fields seems to be integer (_location_id_ is probably an integer). Please verify against your table.
I am trying following code:
try
{
SqlConnection conn = new SqlConnection("server=ARSLAN-LAPI\\SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"database=OTTS; " +
"connection timeout=30");
conn.Open();
String name=UserName.Text;
String pwd=Password.Text;
String query = "INSERT INTO dbo.user (username,password)
VALUES(#username,#password)";
SqlCommand command = new SqlCommand(query, conn);
command.Parameters.Add("#username",name);
command.Parameters.Add("#password",pwd);
command.ExecuteNonQuery();
conn.Close();
ErrorMessage.Text="Well done!";
}
catch(SqlException ex)
{
ErrorMessage.Text="You failed!" + ex.Message;
}
Received error that
You failed!Incorrect syntax near the keyword 'user'.
Please guide me..
User is a reserved keyword, I strongly suggest to change that field name to something different.
However, if you still insist in using it, remember to enclose it in square brackets every time you need it.
string query = "INSERT INTO [dbo].[user] (username,password) VALUES(#username,#password)";
Try this:
INSERT INTO dbo.[user] (username,password) VALUES(#username,#password)
try something like this,
SqlCommand command = new SqlCommand(query, conn);
command.Parameters.Add("#username",SqlDbType.VarChar,50).Value = name;
command.Parameters.Add("#password",SqlDbType.VarChar,50).Value= pwd;
command.ExecuteNonQuery();
I'm trying to do UPDATE the data, but it is showing an error.
protected void Button2_Click(object sender, EventArgs e)//Update
{
{
SqlConnection con = new SqlConnection(#"Data Source=SYSTEM2\SQLEXPRESS;Initial Catalog=amresh;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE detail SET name='" + TxtBox_name.Text + "',address='" + TexBo_add.Text + "', WHERE contact_no='" + TexBo_num.Text + "'",con);
con.Open();
cmd.ExecuteNonQuery();
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('record updated');", true);
con.Close();
}
}
Ooh, so many errors in such a tight space:
the actual SQL error is just an unnecessary comma
but: you have SQL injection problems
and a missing dispose
I'm a big fan of using tools to help avoid pain. Here's the same using "dapper"'
using(var con = new SqlConnection(ConnectionString))
{
con.Execute(#"update detail
set name=#name, address=#address
where contact_no = #num",
new {
name = TxtBox_name.Text,
address = TexBo_add.Text,
num = TexBo_num.Text
});
}
Additionally, it might also want to be:
...
num = int.Parse(TexBo_num.Text)
...
But then - having code that mentions both UI controls and data access in the same method probably means your UI code is doing too much.
First of all Little Bobby Tables would be all over this like a cheap suit. Secondly, look at the documenation of SqlCommand for an example of how to update using parameters.
You need to remove the ,(comma) before where.
SqlCommand cmd = new SqlCommand("UPDATE detail SET name='" + TxtBox_name.Text + "',address='" + TexBo_add.Text + "', WHERE contact_no='" + TexBo_num.Text + "'", con);
^
But I would recommend you to please use Parameterized query.
string query= "UPDATE detail SET name=#name, address=#address WHERE contact_no=#contactno";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#name", TxtBox_Name.Text);
cmd.Parameters.AddWithValue("#address", TexBo_add.Text);
cmd.Parameters.AddWithValue("#contactno", TexBo_num.Text);
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE(ID= '" +
txtStudentIDnumber.Text + "')";
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
In your command text you need to remove single quotes (') around the txtStudentIDnumber.Text as it appears ID is of type integer and you are passing it as string. Following should fix the error.
system.CommandText = "DELETE FROM Student WHERE(ID= " + txtStudentIDnumber.Text + ")";
EDIT: With respect to #mdb comments, you should always use Parameters in your query so that you can avoid SQL Injection. Consider the following:
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID = ?";
OleDbParameter parameter = new OleDbParameter("ID", txtStudentIDnumber.Text);
system.Parameters.Add(parameter);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID=#ID";
system.Parameters.AddWithValue("#ID", txtStudentIDnumber.Text);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
What will happen when user input for txtStudentIDNumber is,
1 or 1=1
In that case hardcoded SQL string will be,
DELETE FROM Student WHERE(ID=1 or 1=1)
So prefer parameterized sql statement instead of hard-coded string.
using(OleDbConnection cn=new OleDbConnection(cnStr))
{
using(OleDbCommand cmd=new OleDbCommand())
{
cmd.CommandText="DELETE FROM Student WHERE ID=#ID";
cmd.Connection=cn;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value=txtStudentIDnumber.Text;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}