{
String Source = @" Data Source = (LocalDB)\MSSQLLocalDB;" + @"AttachDbFilename=c:\users\meghanaa\source\repos\datagrid\datagrid\trialdatabase.mdf;" + "Integrated Security = True";
SqlConnection con_2 = new SqlConnection(Source);
con_2.Open();
for (int i = 0; i < dgv1.Rows.Count; i++)
{
cmd = new SqlCommand(@"INSERT INTO Table([sl],[quetions]) VALUES(@"+dgv1.Rows[i].Cells["sl"].Value+" , @"+dgv1.Rows[i].Cells["questions"].Value+",@"+ dgv1.Rows[i].Cells["op A"].Value + ")",con_2);
cmd.ExecuteNonQuery();
con_2.Close();
MessageBox.Show("data saved");
}
}
Asked
Active
Viewed 51 times
-3

Ashkan Mobayen Khiabani
- 33,575
- 33
- 102
- 171
-
5Before answering the question, I'll strongly suggest to read more about how to avoid `SQL injection`. Your code is opened to this kind of attack, so it's better to consider using **parameters** when doing any operation with your database. – Kaj Jun 15 '18 at 09:49
-
Please show us the error that is given to you. – Lorelorelore Jun 15 '18 at 10:07
-
1Table is a reserved word - hence its complaining because you called your table "table" – BugFinder Jun 15 '18 at 10:15
-
Possible duplicate of [What are good ways to prevent SQL injection?](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection) – mjwills Jun 15 '18 at 10:38
-
By the way, if you pass the first problem, you'll face another problem. You are selecting two columns in your database to insert data into, but you are passing three arguments ! where the third parameter will fit ? – Kaj Jun 15 '18 at 13:21
1 Answers
2
The issue is due the the Table
name given to your database table. In most RDBMS, this is reserved word. Ideally, you should avoid using this in naming your database objects. Refer this link for list of reserved words in SQL Server.
If you still want to use it OR cannot change it anymore, try putting it in square bracket like [Table]
.
Apart from the question you asked, you have another major issue in your code. Your code is susceptible to SQL Injection Attack. Please consider using parameter queries. If you are interested in using any ORM (even simpler like Dapper), that handles this issue and also promotes many best practices.

Amit Joshi
- 15,448
- 21
- 77
- 141