foreach (GridViewRow g1 in GridView1.Rows)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Order VALUES(#buyersName, #deliveryAddress, #productID, #productName, #category, CONVERT(VARBINARY(MAX), #image), #price, #paymentMode, #holderName)", con);
cmd.Parameters.AddWithValue("#buyersName", Label2.Text);
cmd.Parameters.AddWithValue("#deliveryAddress", TextBox1.Text);
cmd.Parameters.AddWithValue("#productID", g1.Cells[0].Text);
cmd.Parameters.AddWithValue("#productName", g1.Cells[1].Text);
cmd.Parameters.AddWithValue("#category", g1.Cells[2].Text);
cmd.Parameters.AddWithValue("#image", g1.Cells[3].Text);
cmd.Parameters.AddWithValue("#price", g1.Cells[4].Text);
cmd.Parameters.AddWithValue("#paymentMode", checkRadioButton());
cmd.Parameters.AddWithValue("#holderName", TextBox2.Text);
int r = cmd.ExecuteNonQuery();
}
When I run this code, it is showing an error that there is a syntax error near "Order". checkRadioButton() is returning the label of the selected RadioButton.
you can't have expression like convert() within the VALUE ()
Change to use
INSERT INTO [Order] (column name, ...)
select #buyersName, convert() ,...
by the way you should explicitly specify the column name in the INSERT clause or in future when you add a column to the table, your query will break
also why are you using reserved name as table name ?
Contrary to the statement in the other answer, it should be possible to CONVERT within the VALUES-section.
But there are multiple flaws or things that could be improved:
ORDER is a reserved word in sql server, put it in square brackets: [Order]
Don't use AddWithValue otherwise sql server infers the datatype, which could be problematic. Use Add instead. See here for more information.
You can convert the value of g1.Cells[3].Text to a byte-array (byte[]) before setting the parameter value. For conversion to byte[] see here.
Specify the columns in your query, to not break it when table changes in future
Change your code like following (column-names and datatypes may vary):
SqlCommand cmd = new SqlCommand(#"INSERT INTO [Order] (buyersName, deliveryAddress, productID, productName, category, image, price, paymentMode, holderName)
VALUES(#buyersName, #deliveryAddress, #productID, #productName, #category, #image, #price, #paymentMode, #holderName)", con);
cmd.Parameters.Add("#buyersName", SqlDbType.VarChar).Value = Label2.Text;
cmd.Parameters.Add("#deliveryAddress", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#productID", SqlDbType.VarChar).Value = g1.Cells[0].Text;
cmd.Parameters.Add("#productName", SqlDbType.VarChar).Value = g1.Cells[1].Text;
cmd.Parameters.Add("#category", SqlDbType.VarChar).value = g1.Cells[2].Text;
cmd.Parameters.Add("#image", SqlDbType.VarBinary).Value = g1.Cells[3].Text; //convert g1.Cells[3].Text to a byte array
cmd.Parameters.Add("#price", SqlDbType.Money) = g1.Cells[4].Text;
cmd.Parameters.Add("#paymentMode", SqlDbType.VarChar).Value = checkRadioButton();
cmd.Parameters.Add("#holderName", SqlDbType.VarChar).Value = TextBox2.Text;
int r=cmd.ExecuteNonQuery();
Related
I keep getting the error in the title when i am trying to pass data to my database using a c# windows form.
For reference, I am trying to use the Scope_Identity to get the current PK from one table and then pass it to another table as a FK. But i am having trouble making this work. I have no doubt I am missing something or doing something wrong, but I honestly cannot find a solution to what I need. Here is the code I am using.
SqlConnection con = new SqlConnection(#"");
con.Open();
{
using (SqlCommand cmd = new SqlCommand("INSERT dbo.Booking(CustomerID,VehicleID,DateofBooking," +
"DurationBooked, ExpectedReturnDate) VALUES( #CustID, #VehicleID, #DOBooking, #DurationBooked,#ExpectedReturn); INSERT dbo.Payments (BookingID,PaymentMethod,Discount,PaymentAmount," +
"PaymentDate,PaymentReceived) VALUES( SCOPE_IDENTITY(),#PayMeth,#PayAmount,#PayDate, #PayReceived, #Discount)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#CustID", SqlDbType.Int).Value = comboBox1.ValueMember;
cmd.Parameters.Add("#VehicleID", SqlDbType.Int).Value = comboBox2.ValueMember;
cmd.Parameters.Add("#DOBooking", SqlDbType.Date).Value = datefrom.Text;
cmd.Parameters.Add("#ExpectedReturn", SqlDbType.Date).Value = dateTo.Text;
cmd.Parameters.Add("#DurationBooked", SqlDbType.Float, 3).Value = Duration.Text;
cmd.Parameters.Add("#PayMeth", SqlDbType.VarChar, 15).Value = listBox1.Text;
cmd.Parameters.Add("#PayAmount", SqlDbType.Money).Value = PayAmount.Text;
cmd.Parameters.Add("#PayDate", SqlDbType.Date).Value = DatePay.Text;
cmd.Parameters.Add("#PayReceived", SqlDbType.VarChar, 3).Value = PayReceived.Text;
cmd.Parameters.Add("#Discount", SqlDbType.SmallMoney).Value = Discount.Text;
}
I am having a ridiculous amount of hassle trying to Pass this PK to another Table as a FK For reference, it is the BookingID from the Booking table that i am trying to pass to the Payments table in the BookingID column which is a FK relationship
Error Image
I think you're trying to fight with a different problem.
you have conversion issue, but not PK or FK key consistency.
please check if all the params they you send have the same type as described in your instruction.
It can be also that even your scope_identity() has type different from value.
I don't know if you covered this with Keys constraints
by the way. out of scope. There is also a way to get last id is to use ##IDENTITY.
The ##identity function returns the last identity created in the same session. The scope_identity() function returns the last identity created in the same session and the same scope.
FIXED. Thank you to all those who helped. The issue was indeed with my Parameters, specifically with dates. I needed to change the DataType in SQL server to DateTime, as well as ensuring the query would run in SQL Server first helped.
using (SqlCommand cmd = new SqlCommand("INSERT dbo.Booking(CustomerID,VehicleID,DateofBooking, DurationBooked, ExpectedReturnDate) " +
"VALUES( #CustID, #VehicleID, #DOBooking, #DurationBooked,#ExpectedReturn) SELECT SCOPE_IDENTITY(); " +
"INSERT dbo.Payments (BookingID,PaymentMethod,Discount,PaymentAmount, PaymentDate,PaymentReceived)" +
"VALUES( SCOPE_IDENTITY(),#PayMeth,#Discount,#PayAmount, #PayDate, #PayReceived)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#CustID", SqlDbType.Int).Value = Convert.ToInt32(CustID.SelectedValue);
cmd.Parameters.Add("#VehicleID", SqlDbType.Int).Value = Convert.ToInt32(VehicleID.SelectedValue);
cmd.Parameters.Add("#DOBooking", SqlDbType.DateTime).Value = DateofBooking.Value.Date;
cmd.Parameters.Add("#ExpectedReturn", SqlDbType.DateTime).Value = ExpectedReturnDate.Value.Date;
cmd.Parameters.Add("#DurationBooked", SqlDbType.Float, 3).Value = Duration.Text;
cmd.Parameters.Add("#PayMeth", SqlDbType.VarChar, 15).Value = PaymentMethod.Text;
cmd.Parameters.Add("#PayAmount", SqlDbType.Money).Value = PayAmount.Text;
cmd.Parameters.Add("#PayDate", SqlDbType.DateTime).Value = PayDate.Value.Date;
cmd.Parameters.Add("#PayReceived", SqlDbType.VarChar, 3).Value = Received.Text;
cmd.Parameters.Add("#Discount", SqlDbType.VarChar, 3).Value = Discount.Text;
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Customer failed");
}
For Ref, Scope_Identity worked perfectly.
Thanks for all your support, I know this may seem basic for some of you, but i am new to all this and trying to self teach, so as you can imagine.. it was a relief even this little issue is solved. Thanks guys
How can I get this query to work? keep getting this error:
"syntax error in INSERT INTO statement"
I am confused as it used to work on another program, but I got all scrambled up with this one.
string item = listView1.Items[listView1.FocusedItem.Index].Text;
MessageBox.Show(item); //test Value
string thisDay1 = DateTime.Now.ToString();
ad.InsertCommand = new OleDbCommand("INSERT INTO Scrap-Rework Master Data (Is_today, S_Line, Status, T_Number, Test_Cp, think_a, Rew_Hos, QAffect, Comments)
values (?, ?, ?, ?, ?, ?, ?, ?, ?)", con);
ad.InsertCommand.Parameters.AddWithValue("#S_Line", OleDbType.VarChar).Value = textBox1.Text;
ad.InsertCommand.Parameters.AddWithValue("#Status", OleDbType.VarChar).Value = domainUpDown1.Text;
ad.InsertCommand.Parameters.AddWithValue("#T_Number", OleDbType.VarChar).Value = textBox2.Text;
ad.InsertCommand.Parameters.AddWithValue("#Test_Cp", OleDbType.VarChar).Value = item;
ad.InsertCommand.Parameters.AddWithValue("#think_a", OleDbType.VarChar).Value = domainUpDown2.Text;
ad.InsertCommand.Parameters.AddWithValue("#Rew_Hos", OleDbType.Numeric).Value = Double.Parse(textBox4.Text);
ad.InsertCommand.Parameters.AddWithValue("#QAffect", OleDbType.Numeric).Value = int.Parse(textBox3.Text);
ad.InsertCommand.Parameters.AddWithValue("#Comments", OleDbType.VarChar).Value = textBox5.Text;
ad.InsertCommand.Parameters.AddWithValue("#Is_today", OleDbType.DBTime).Value = thisDay1;
Listview has 2 columns:
ListViewItem listitem = new ListViewItem(dr["Test_Cp"].ToString());
listitem.SubItems.Add(dr["Description"].ToString());
fields on access database and type:
S_Line -Short Text;
Status -Short Text;
T_Number -Short Text;
Test_Cp -Short Text;
think_a -Short Text;
Rew_Hos -Number;
QAffect -Number;
Comments -Long Text;
Is_today -Date/Time;
Thank you so much in advance.
First you must use brackets [] always for the name that contains spaces in query like [Scrap-Rework Master Data].
2- Declare OleDbCommand parameter.
3- Put name of Parameters in query with respect order.
4- Format DateTime field.
5- add cmd.ExecuteNonQuery(); for insert data.
string item = listView1.Items[listView1.FocusedItem.Index].Text;
MessageBox.Show(item); //test Value
OleDbCommand cmd = new OleDbCommand("INSERT INTO [Scrap-Rework Master Data] (S_Line, Status, T_Number, Test_Cp, think_a, Rew_Hos, QAffect, Comments, Is_today)" +
"values(#S_Line, #Status, #T_Number, #Test_Cp, #think_a, #Rew_Hos, #QAffect, #Comments, #Is_today)", con);
cmd.Parameters.AddWithValue("#S_Line", textBox1.Text);
cmd.Parameters.AddWithValue("#Status", domainUpDown1.Text);
cmd.Parameters.AddWithValue("#T_Number", textBox2.Text);
cmd.Parameters.AddWithValue("#Test_Cp", item) ;
cmd.Parameters.AddWithValue("#think_a", domainUpDown2.Text);
cmd.Parameters.AddWithValue("#Rew_Hos", Double.Parse(textBox4.Text)) ;
cmd.Parameters.AddWithValue("#QAffect", int.Parse(textBox3.Text)) ;
cmd.Parameters.AddWithValue("#Comments", textBox5.Text) ;
cmd.Parameters.AddWithValue("#Is_today", DateTime.Now.ToString("#yyyy/MM/dd#"));
cmd.ExecuteNonQuery();
You're using OleDB, so you can't use named parameters:
System.Data.OleDb
Uses positional parameter markers indicated by a question mark (?).
which means (from same page)
As a result, the order in which Parameter objects are added to the Parameters collection must directly correspond to the position of the ? placeholder for the parameter.
The problem is your order is wrong: the first value in your INSERT is Is_Today, but that's the last value you add to the parameter array. Hence all the value types are wrong. Try moving
ad.InsertCommand.Parameters.AddWithValue("#Is_today", OleDbType.DBTime).Value = thisDay1;
to the head of your parameter add list.
Also I agree with abrown's comment: you'll likely need to bracket the table name [Scrap-Rework Master Data] since it has spaces and a dash in it.
Try to use stored procedure in DB:
using (var command1 = new SqlCommand("InsertData", conn)
{
CommandType = CommandType.StoredProcedure
})
{
command1.Parameters.Add("#a1", SqlDbType.Text).Value = A1;
command1.Parameters.Add("#a2", SqlDbType.Text).Value = A2;
command1.Parameters.Add("#a3", SqlDbType.Text).Value = A3;
command1.Parameters.Add("#a4", SqlDbType.Text).Value = A4;
command1.ExecuteNonQuery();
}
Hey I get an error saying there is something wrong with my code when inserting into a database, can't quite find it. The error suggests it is something in the INSERT statement, but appears on the line "cmd.ExecuteNonQuery();". I'm using an access database.
Error: Syntax error in INSERT INTO statement.
con.Open();
string mysql;
mysql = "INSERT INTO [User](FirstName,Surname,Age,HouseNumber,PostCode,Username,Password)
VALUES (?,?,?,?,?,?,?)";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddWithValue("#p1", tbFirstName.Text);
cmd.Parameters.AddWithValue("#p2", tbSurname.Text);
cmd.Parameters.AddWithValue("#p3", int.Parse(tbAge.Text));
cmd.Parameters.AddWithValue("#p4", tbAddress1.Text);
cmd.Parameters.AddWithValue("#p5", tbPostCode.Text);
cmd.Parameters.AddWithValue("#p6", tbUsername.Text);
cmd.Parameters.AddWithValue("#p7", tbPassword.Text);
cmd.ExecuteNonQuery();
con.Close();
when you add parameters with value you need to convert it to matching type, if age is number then
cmd.Parameters.AddWithValue("#p3", int.Parse(tbAge.Text));
and also User is key word you can try with
"INSERT INTO [User] ([FirstName], [Surname], [Age], [HouseNumber], [PostCode], [Username], [Password]) VALUES (?,?,?,?,?,?,?)";
Have you tried replacing the ? with your parameters?
Correction: I believe you have to add OleDBParameters like so:
con.Open();
string mysql;
mysql = "INSERT INTO User(FirstName,Surname,Age,HouseNumber,PostCode,Username,Password)
VALUES (#p1,#p2,#p3,#p4,#p5,#p6,#p7)";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#p1", tbFirstName.Text),
new OleDbParameter("#p2", tbSurname.Text),
...
});
cmd.ExecuteNonQuery();
con.Close();
Platform used : Microsoft Visual Studio 2010 (C#)
Database : SQL Server 2008 R2 Express
I want to get the text from the drop down and put it into database table. I am getting error saying
Invalid column name 'Type'.
though column is present in database table.
da.InsertCommand = new SqlCommand("insert into tblProductMaster ([Name],[Type],[Height],[Width],[Length],[Price]) values( #Name , #Type , #Height , #Width , #Length , #Price )", con);
da.InsertCommand.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text;
da.InsertCommand.Parameters.Add("#Type", SqlDbType.VarChar, 10).Value = ddlType.SelectedItem.ToString();
da.InsertCommand.Parameters.Add("#Height", SqlDbType.Float).Value = float.Parse(txtHeight.Text);
da.InsertCommand.Parameters.Add("#Width", SqlDbType.Float).Value = float.Parse(txtWidth.Text);
da.InsertCommand.Parameters.Add("#Length", SqlDbType.Float).Value = float.Parse(txtLength.Text);
da.InsertCommand.Parameters.Add("#Price", SqlDbType.SmallMoney).Value = int.Parse(txtPrice.Text);
da.InsertCommand.ExecuteNonQuery();
I believe your problem is that you are using a SQL Server reserved word ("Size") and you have not properly encapsulated it in your INSERT statement.
Try this:
da.InsertCommand = new SqlCommand("insert into tblProductMaster ([Name], [Size], [Height], [Width], [Length], [Price]) values(#Name, #Size, #Height, #Width, #Length, #Price)", con);
Notice the [ & ] around the column names... this will tell SQL Server to treat them as columns.
WARNING: I highly recommend you change these column names if you can. Using reserved words of any product is very poor database design and will continue to cause you problems and/or extra work. Better to fix it sooner than later.
#Sagar try this
string strCmd = #"insert into tblProductMaster ([Name], [Size], [Height], [Width], [Length], [Price]) values(#Name, #Size, #Height, #Width, #Length, #Price)";
Then
SqlCommand cmd = new SqlCommand(strCmd, con);
cmd.Parameters.Add("#Size", SqlDbType.VarChar, 10, ddlSize.SelectedItem.Value.ToString());
da.InsertCommand = cmd;
I'm using the following code and it is giving the invalid Insert command exception.
row the DataRow object to be added to the database , conn is the OleDBConnection object.
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = `"Insert Into Appointments(ID,Body,End,Location,Start,Subject,Properties)"
+ "Values(#ID,#Body,#End,#Location,#Start,#Subject,#Properties)";
cmd.Parameters.Add("#ID", OleDbType.WChar).Value = row[0].ToString();
cmd.Parameters.Add("#Body", OleDbType.WChar).Value = row[1].ToString();
cmd.Parameters.Add("#End", OleDbType.Date).Value = Convert.ToDateTime(row[2]).Date.ToLongDateString();
cmd.Parameters.Add("#Location", OleDbType.WChar).Value = row[3].ToString();
cmd.Parameters.Add("#Start", OleDbType.Date).Value = Convert.ToDateTime(row[4]).Date.ToLongDateString();
cmd.Parameters.Add("#Subject", OleDbType.WChar).Value = row[5].ToString();
cmd.Parameters.Add("#Properties", OleDbType.WChar).Value = row[6].ToString();
conn.Open();
cmd.ExecuteNonQuery(); //At this line exception is generating
conn.Close();
Please help me in this.
You've got one (possibly more) reserved word in your table's field names.
The field name End ... at the very least.
Try
cmd.CommandText = `"Insert Into Appointments(ID,Body,[End],Location,Start,Subject,Properties)"
+ "Values(#ID,#Body,#End,#Location,#Start,#Subject,#Properties)";
Does "Appointments" table support inserting ID? If ID column is the identity value, that may cause problem.
I think that the data-types that you use for your parameters are incorrect.
If your ID column is a numeric column, you shouldn't use OleDbType.WChar, but OleDbType.Integer, for instance
For alfanumeric-columns, I wouldn't use OleDbType.WChar either, but OleDbtype.VarChar.
See the OleDbType enumeration as well.