Click here to Skip to main content
15,891,923 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to insert combobox values into access database using C# windows application. It allows only one combobox to insert value into the database. How can I insert more than one combobox value into the database.

What I have tried:

C#
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.Oledb.12.0; Data Source= school.accdb");
                string query = "Insert into stu_registration (CLASS, SECTION) values ('" + comboBox101.Text + "', '"+comboBox102.Text+"')";
                
                
                OleDbCommand cmd = new OleDbCommand(query, con);
                


                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
Posted
Updated 29-Mar-20 21:11pm
v2

Two things:

1) Your code is sql injection[^] vulnerable!
You should avoid of using concatenated string as a query. Use parameterized queries instead.

C#
string sConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\school.accdb;Persist Security Info =False;";
DataTable dt = new DataTable();

//student id to find
int stuIdToFind = 111; 
//select statement
string sComm = "SELECT Stu.* FROM Students AS Stu WHERE Stu.StuId=?;";

using (OleDbConnection oConn = new OleDbConnection(sConn))
	{
		oConn.Open();
		using (OleDbCommand oComm  = new OleDbCommand(sComm, oConn))
		{
			//add parameter with value
			oComm.Parameters.Add(new OleDbParameter(){Value=stuIdToFind});
			using (OleDbDataReader oRdr = oComm.ExecuteReader())
			{
				dt.Load(oRdr);
			}
		}
	}



2) You're using SECTION as a field name but(!) this word is one of reserved words in MS Access.
See: List of reserved words in Access - Office | Microsoft Docs[^]
I'd suggest to change a field name or use square brackets around a field name:
SQL
SELECT [SECTION] FROM YourTableName;
 
Share this answer
 
v2
In addition to the very accurate comments by Maciej, You can insert multiple rows (if that's what you are trying to do in several ways:
1) Use a multiple INSERT
C#
INSERT INTO MyTable (Col1, Col2) VALUES (1, 2), (3, 4), 5, 6)
But in your case that's still goingh to be SQL Injection vulnerable.
2) Do your INSERT operation in a loop.
3) Use a DataTable and INSERT via a DataAdapter: c# - Insert dataset records in database - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900