Error connecting to MS Access database from C# Winform - c#

I'm a student programmer and I'm writing this software for a small school, it's my first program, the code below is giving me the error
syntax error in insert into statement
I know the connection string is not the problem because I use it for inserting into two other tables with the same insert into format.
I am using an access database.
The offending code is
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into studentBillRecords (StudentName, Department, Level, AccomodationStatus, SemesterBill, PreviousBalance, TotalBill) values ('"+ txtSRstudentName.Text + "', '" + cmbSRDepartment.Text + "', '" + cmbSRLevel.Text + "', '" + cmbSRAccomodationStatus.Text + "', '" + txtSRSemesterBill.Text + "', '" + txtSRPreviousBalance.Text + "', '" + txtSRTotalBill.Text + "')";
MessageBox.Show(command.CommandText);
command.ExecuteNonQuery();
connection.Close();
This same code with different table names, column names and input works with another table in the same database but won't work with this one.

Level is a reserved keyword in access.
Also use Parameters instead of concatinating string. Try this code out, it makes it safer and easier to read:
Note: I changed the name of the column Level to StudentLevel which, I assume, doesn't exist yet in your table.
try
{
using (OleDbConnection connection = new OleDbConnection("my connection string"))
{
//Open connection
connection.Open();
//Create new command
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
//Create command text
cmd.CommandText =
"INSERT INTO studentBillRecords " +
"(StudentName, Department, StudentLevel, AccomodationStatus, SemesterBill, PreviousBalance, TotalBill) VALUES " +
"(#StudentName, #Department, #StudentLevel, #AccomodationStatus, #SemesterBill, #PreviousBalance, #TotalBill)";
// Add names paremeters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#StudentName", txtSRstudentName.Text),
new OleDbParameter("#Department", cmbSRDepartment.Text),
new OleDbParameter("#StudentLevel", cmbSRLevel.Text),
new OleDbParameter("#AccomodationStatus", cmbSRAccomodationStatus.Text),
new OleDbParameter("#SemesterBill", txtSRSemesterBill.Text),
new OleDbParameter("#PreviousBalance", txtSRPreviousBalance.Text),
new OleDbParameter("#TotalBill", txtSRTotalBill.Text)
});
//Execute Query
cmd.ExecuteNonQuery();
//No need to close because we are using "using"
}
}
catch (OleDbException ex)
{
//If an exception occurs let's print it out to console
Console.WriteLine("ERROR: " + ex.ToString());
throw;
}
For information on how to change the column name read this:
https://msdn.microsoft.com/en-us/library/bb177883(v=office.12).aspx

"Level" is a keyword in MS Access, may be that is why this issue occurs try quoting it like [Level]
List Of MS Access Keywords

Related

C# MS Access Database Update with Dynamic Column Name

I am trying to push data into a column where the name is a variable.
From the code below:
label1.Text is the dynamic column of the DB database (it is a string)
ComboBox1.Text is the data that I want to put into the dynamic column (column name = label1.Text)
connection.Open();
OleDBCommand command = new OleDbCommand();
command.Connection = connection;
command.ConnectionText = "update DB set column1='" + richTextBox1.Text + "', " + label1.Text + " = '" + comboBox1.Text + "' where ID=" + label2.Text;
command.ExecuteNonQuery();
connection.Close();
I have tried many different things such as moving the single quotes and double quote locations, add the & sign for the string concatenation. But all I have been able to do is push the label1.Text, ComboBox1.Text, and richTextBox1.Text all into column1...
This is only a small portion of my code, so please let me know if you have questions.

How to get all records from one table and save it on another table by c# in winforms?

Hello guys, i am trying to get all records from tblInvoiceItemsTemp table and save all the records inside the tblInvoiceItems table but not able to solve. Any help would be appreciated, thank you.
I have added following code on btnSave_Click() event.
string connetionString1 = "server=localhost;database=billingDB;uid=root;pwd=root;integrated security=true";
using (MySqlConnection cnn1 = new MySqlConnection(connetionString1))
{
cnn1.Open();
string load_temp_table_rec_qry = "SELECT * FROM tblInvoiceItemsTemp";
using (MySqlCommand sqlcmd = new MySqlCommand(load_temp_table_rec_qry, cnn1))
{
MySqlDataReader temp_reader = sqlcmd.ExecuteReader();
while (temp_reader.Read())
{
string insert_invoice_items_qry = "INSERT INTO tblInvoiceItems(invoiceID, particulars, qty, rate) VALUES('" + 12 + "', '" + temp_reader["particulars"] + "', '" + temp_reader["qty"] + "', '" + temp_reader["rate"] + "')";
using (MySqlCommand itemsCmd = new MySqlCommand(insert_invoice_items_qry, cnn1))
{
itemsCmd.ExecuteNonQuery();
}
}
}
cnn1.Close();
}
I am getting following error messages.
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional Information: There is already an open DataReader associated with this Connection which must be closed first.
The error message is pretty clear: while you have a DataReader open (you haven't called Close/Dispose), the Connection cannot be used for anything else. One way to do this is to open a second connection:
using (MySqlCommand sqlcmd = new MySqlCommand(load_temp_table_rec_qry, cnn1))
{
MySqlDataReader temp_reader = sqlcmd.ExecuteReader();
using (var secondConnection = new MySqlConnection(connetionString1))
{
secondConnection.Open();
while (temp_reader.Read())
{
string insert_invoice_items_qry = "INSERT INTO tblInvoiceItems(invoiceID, particulars, qty, rate) VALUES('" + 12 + "', '" + temp_reader["particulars"] + "', '" + temp_reader["qty"] + "', '" + temp_reader["rate"] + "')";
using (MySqlCommand itemsCmd = new MySqlCommand(insert_invoice_items_qry, secondConnection))
{
itemsCmd.ExecuteNonQuery();
}
}
}
}
Another way is to use the disconnected model and load the records to a DataTable using a MySqlDataAdapter, so that the connection is free for using for itemsCmd.
However, you don't need to download into memory all the records for this, you can do an INSERT INTO SELECT, for much better performance:
INSERT INTO tblInvoiceItems(invoiceID, particulars, qty, rate)
SELECT 12, tblInvoiceItemsTemp.particulars, tblInvoiceItemsTemp.qty, tblInvoiceItemsTemp.rate
FROM tblInvoiceItemsTemp

OleDb Exception

For 5 hour searching i can't find my mistake. I get this exception. What is wrong?
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in MyDictionary.exe
Additional information: Syntax error in INSERT INTO statement.
My code:
public void Insert(Word word)
{
string language=FindLanguage();
try
{
command.CommandText ="INSERT INTO "+language+" ( Native , Foreign , Definition , AddingDate) values ( '" + word.Native + "' , '" + word.Foreign + "' , '" + word.Definition + "' ,'" + word.AddingDate + "')";
command.CommandType = System.Data.CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
You should use parameters in your insert statement.Also looks like you are missing command.Connection = connection;.
Note that your SQL is prone for SQL Injection
command.CommandText ="INSERT INTO "+language+"([Native],[Foreign],[Definition],[AddingDate]) VALUES (#Native,#Foreign,#Definition,#AddingDate)";
command.Parameters.AddWithValue("#Native", word.Native);
command.Parameters.AddWithValue("#Foreign",word.Foreign);
command.Parameters.AddWithValue("#Definition",word.Definition);
command.Parameters.AddWithValue("#AddingDate",word.AddingDate);
command.CommandType = System.Data.CommandType.Text;
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
In OleDb the correct syntax of the INSERT INTO statement involves usage of the SELECT clause even though you're appending static values. So you need to change your query like bellow example.
Further, don't construct try...catch..finally if you don't actually handle a raised exception. In the sake of disposal use using() { } block instead. So here it is:
public void Insert(Word word)
{
string language=FindLanguage();
using (var connection = new OleDbConnection("connection string goes here"))
using (var command = new OleDbCommand...)
{
command.CommandText = #
"INSERT INTO " + language + "(Native, Foreign, Definition, AddingDate)" +
"SELECT '"
+ word.Native + "' AS Native, '"
+ word.Foreign + "' AS Foreign, '"
+ word.Definition + "' AS Definition, '"
+ word.AddingDate + "' AS AddingDate"
;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}

Why am I getting a Datatype Mismatch error in C# Windows Forms Application

I have created a simple application every thing is working fine except update
portion insertion is working fine with same table data
My code is
private void button2_Click(object sender, EventArgs e)
{
string cmd = ("UPDATE submissionFee SET [stdName]='" + textBox2.Text + "', [fatherName]='" + textBox3.Text + "', [program]='" + textBox4.Text + "', [adress]='" + textBox5.Text + "',[email]='" + textBox6.Text + "', [cellNum]='" + textBox7.Text + "', [isPaid] = '" + textBox8.Text + "', [SubmissionDate] = '" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "'Where [ID]='" + textBox1.Text + "'");
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = cmd;
command.ExecuteNonQuery();
MessageBox.Show("Account Has Been Updated");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
MessageBox.Show("Please Enter Valid Data");
}
}
Error Screenshot
Probably the connection is already open when you try to open it.
Either:
1) Make sure you close the connection from the last time you used it.
2) Or, if it is sometimes supposed to be kept open, check if the connection is already open, and don't close it if it is. Something like:
bool bWasOpen = (connnection.State == ConnectionState.Open);
if (!bWasOpen)
connection.Open();
...
if (!bWasOpen)
connection.Close();
Much Worse than the crash: Your code is volunerable to Sql-injection.
--> Use parameterized sql.
The reason for this exception in the dialog is due to the connection state is already open; and hence it cannot be opened again. You must close the connection in your previous statement. Or, check if the connection closed, and then open it.
Some other tips to you is
Do not use Textbox1, Textbox2 etc., give them proper ID like txtStudentId, txtFatherName etc.,
User SQL Parameters to pass the values to your database. check the sample statements below
String query = "UPDATE submissionFee SET stdName=#stdName, fatherName=#fatherName where id=#id;";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id",txtID.txt); command.Parameters.Add("#stdName",txtStudent.Text); command.Parameters.Add("#fatherName",txtFatherName.Text);
command.ExecuteNonQuery();
Please use using statement when You query to database.
Why? Simple... it has implemented IDisposable.
P.S.
Use parameterized query to protect against SQL Injection attacks.
string insertStatement = UPDATE submissionFee SET stdName=#stdName,fatherName=#fatherName,program=#program,adress=#adress,email=#email,cellNum=#cellNum,isPaid=#isPaid,SubmissionDate=#SubmissionDate,ID=#ID
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(insertStatement, connection))
command.Parameters.AddWithValue("#ID",textBox1.Text);
command.Parameters.AddWithValue("#stdname",textbox2.Text);
command.Parameters.AddWithValue("#fathername",textBox3.Text);
command.Parameters.AddWithValue("#program",textBox4.Text);
command.Parameters.AddWithValue("#adress",textBox5.Text);
command.Parameters.AddWithValue("#email",textBox6.Text);
command.Parameters.AddWithValue("cellNum",textBox7.Text);
command.Parameters.AddWithValue("#isPaid",textBox8.Text);
command.Parameters.AddWithValue("#SubmissionDate",dateTimePicker1.Value.ToString("MM/dd/yyyy"));
connection.Open();
var results = command.ExecuteNonReader();
}
}
Part of code was taken from this link.

Writing to a database in asp.net

I'm currently finishing an asp.net project for a class and began to notice a major flaw with one of the requisites. The application should ask five questions and write the answers to a database, afterwards it should display the results of the survey to the user.
This is what I have attempted so far:
public static string GetConnectionString()
{
string connStr = String.Format("server={0}; user id={1}; password={2};" + "database= -table to be accessed-; pooling=false",
"-database server-", "-user-", "-password-");
return connStr;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string sex = gender.Text;
string likes = interests.Text;
string edu = education.Text;
string nation = nationality.Text;
string userage = age.Text;
MySql.Data.MySqlClient.MySqlConnection mycon;
mycon = new MySqlConnection(GetConnectionString());
try
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO survey (gender, age, birthplace, occupation, winner) VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')", mycon);
cmd.ExecuteNonQuery();
mycon.Open();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
mycon.Close();
}
}
}
I went ahead and replaced the database information with placeholders.
The database is MySql and hosted on an external server.
The issue I'm experiencing is that the code compiles, however the information does not get written to the database. I'm not certain if this is due to the fact that I'm still testing the code and have not uploaded the web application to the server or the fact that it's just wrong.
As far as displaying the results go, if the above code is correct it would simply be a matter of changing the sql query, correct?
Thanks in advance for the insight.
You are executing the command before opening database connection.
ExecuteNonQuery() method and all other Execute method require an open database connection.
And another error is:
Number of columns (i.e. 5) and provided values (i.e. 4) are not equal.
And one more issue in your code is here as stated by Steve Wellens.
Change Your Code like below:
try
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO survey (gender, age, birthplace, occupation, winner) VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')", mycon);
mycon.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
mycon.Close();
}
Security Notes:
Never add data into query using + operator. It may cause SQL Injection.
What if a user enters 1); DROP TABLE <table-name> -- in Age TextBox..??
Anyone can delete any table entirely from database.
Use MySQL Parameter to avoid such problems. It may prevent from causing serious damages to your entire database.
In your connection string:
"database= -table to be accessed-;
...you don't put the table. The table is specified in the SQL statement.
you should open the connect first, then execute the query.
try
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO survey (gender, age, birthplace, occupation, winner) VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')", mycon);
mycon.Open();
cmd.ExecuteNonQuery();
}
This is likely not the only problem, but it is a problem:
"INSERT INTO survey (gender, age, birthplace, occupation, winner) " +
"VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')",
(I've broken it into two strings to make it easier to read.)
You are inserting into five columns. You are only specifying four data values, and with the exception of gender they don't appear to be in the right order or even be the right data.
try checking these things :
try opening your connection before executing the SQL
check your SQL, and try execute them directly against the database. what i see in your SQL is you are concatenating the values into one string (quotes exist only in beginning and end, but not in between the parameters passed)

Categories

Resources