run multiple SqlCommand and ExecuteNonQuery - c#

I am trying to run multiples SqlCommand in the same connection, but for some reason the program will stop at the second
command.ExecuteNonQuery();
Here is my code :
string queryString = "SELECT DISTINCT Titre from infosHoraire where Salle='DOO';" +
"SELECT DISTINCT Titre from infosHoraire where Salle='FOO' and Jour <='" + finDate + "';" +
"SELECT DISTINCT Titre from infosHoraire where Salle='GOO' and Jour <='" + finDate + "';";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConsoleXMLtoDB"].ConnectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
// on remplit le dico
while (reader.Read())
{
MoviesList.Add(reader[0].ToString(), "0");
searchCode(reader[0].ToString(), MoviesList);
//Console.WriteLine(" On rajoute le code {0}", MoviesList[reader[0].ToString()]);
}
reader.NextResult();
while (reader.Read())
{
if (!MoviesList.ContainsKey(reader[0].ToString()))
{
MoviesList.Add(reader[0].ToString(), "0");
searchCode(reader[0].ToString(), MoviesList);
}
}
reader.NextResult();
while (reader.Read())
{
if (!MoviesList.ContainsKey(reader[0].ToString()))
{
MoviesList.Add(reader[0].ToString(), "0");
}
}
foreach (string key in MoviesList.Keys)
{
Console.WriteLine("MoviesList {0}, code {1} .", key, MoviesList[key]);
// RAJOUTER DONNEES HORAIRES
command.CommandText = "INSERT INTO infosHoraire (Code) VALUES ('" + MoviesList[key] + "') where Titre = '" + key + "'";
//cmd.Parameters.AddWithValue("#code", MoviesList[key]);
IT STOPS HERE.
command.ExecuteNonQuery();
}
}
catch (Exception)
{
//Console.WriteLine("{0} Exception caught.", e);
}
finally
{
// Always call Close when done reading.
reader.Close();
connection.Close();
}
}
MoviesList is a
Dictionary<string, string>
I can't really find where the issue comes from.
It will work fine if I remove this :
foreach (string key in MoviesList.Keys)
{
//literaltest.Text += "<br/> dictionnaire " + key + "," + MoviesList[key];
Console.WriteLine("MoviesList {0}, code {1} .", key, MoviesList[key]);
// RAJOUTER DONNEES HORAIRES
command.CommandText = "INSERT INTO infosHoraire (Code) VALUES ('" + MoviesList[key] + "') where Titre = '" + key + "'";
//cmd.Parameters.AddWithValue("#code", MoviesList[key]);
command.ExecuteNonQuery();
}

Edit: Try to put a breakpoint on your catch and see if there is an error.
catch (Exception e)
{
//Console.WriteLine("{0} Exception caught.", e);
}
Hover your mouse on e and you should be able to see the error message. Then paste it here. Its probably your query causing the problem rather than the command object
Edit. The reader object is still running which is limiting you to use the command object again. Close the reader first before trying to execute the next command
reader.Close();

remove where condition from your following insert query
command.CommandText = "INSERT INTO infosHoraire (Code) VALUES ('" + MoviesList[key] + "') where Titre = '" + key + "'";

The SQLDataReader you used to read records is still open and using that connection. You need to close that reader before executing another command on the same connection. e.g.
reader.Close();
foreach (string key in MoviesList.Keys)
{
Console.WriteLine("MoviesList {0}, code {1} .", key, MoviesList[key]);
// RAJOUTER DONNEES HORAIRES
command.CommandText = "INSERT INTO infosHoraire (Code) VALUES ('" + MoviesList[key] + "') where Titre = '" + key + "'";
//cmd.Parameters.AddWithValue("#code", MoviesList[key]);
IT STOPS HERE.
command.ExecuteNonQuery();
}

Your SQL syntax for the INSERT statement is bad. You just need this
querystring= "INSERT INTO infosHoraire (Code) VALUES ('" + MoviesList[key] + "')";

The SqlCommand (command) is still busy - you can't reuse it for the insert statement. You'd need to open a new SqlConnection with a new SqlCommand. Although it'd probably be cleaner if you just moved your foreach outside of the original queries using block, since you only referencing the in memory dictionary at that point.
As mentioned, your insert statement also has a where clause which doesn't make sense...did you perhaps mean that to be an update statement?
Drop the empty catch and you'll see some exception messages, which will make your life much easier.

//edit your select statement try this
SELECT DISTINCT Titre from infosHoraire where Salle in ('DOO','FOO','GOO') and Jour <='" + finDate + "'";

Related

Exception Unhandled - MySql.Data.MySqlClient.MySqlException

I was gonna save my date and time record in my database when an unhandled exception always thrown at this code: int value = cmd.ExecuteNonQuery(); when I'm clicking the 'Time In' button.
it says that MySql.Data.MySqlClient.MySqlException 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Mar 2022 3:53:00 AM,System.Windows.Forms.DateTimePicker, Value
When I check my codes, there's no errors. I debugged it but no errors appeared.
Here's my codes:
private void btnTimeIn_Click(object sender, EventArgs e)
{
string connectstring = "datasource=localhost;port=3306;username=root;password=;database=employeedb;SslMode=none";
MySqlConnection conn = new MySqlConnection(connectstring);
conn.Open();
string iQuery = "INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`, `RecordDate`, `TimeIn`, `TimeOut`) VALUES (" + txtEmployeeID.Text + "," + txtLstName.Text + "," + txtFirstName.Text + "," + dateTimePicker1.Value + "," + dateTimePicker2 + "," + dateTimePicker3 + ")";
MySqlCommand cmd = new MySqlCommand(iQuery, conn);
int value = cmd.ExecuteNonQuery();
MessageBox.Show(value.ToString());
conn.Close();
}
Your immediate help, tips and advice are highly appreciated
I was gonna expect that I'm gonna save records in my database by timing in... but I can't even find what could be wrong because i just did all ways of inserting data into table in database. Still, I didn't also work, and the exception still throwing every time at the 'cmd.ExecuteNonQuery' line.
This line of code is causing the bug, and can also lead to SQL injection:
string iQuery = "INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`, `RecordDate`, `TimeIn`, `TimeOut`) VALUES (" + txtEmployeeID.Text + "," + txtLstName.Text + "," + txtFirstName.Text + "," + dateTimePicker1.Value + "," + dateTimePicker2 + "," + dateTimePicker3 + ")";
You should always use command parameters, not string concatenation:
using (MySqlConnection conn = new MySqlConnection(connectstring))
{
conn.Open();
string iQuery = #"
INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`,
`RecordDate`, `TimeIn`, `TimeOut`)
VALUES (#id, #last, #first, #date, #in, #out);";
using MySqlCommand cmd = new MySqlCommand(iQuery, conn))
{
cmd.Parameters.AddWithValue("#id", txtEmployeeID.Text);
cmd.Parameters.AddWithValue("#first", txtLstName.Text);
cmd.Parameters.AddWithValue("#last", txtFirstName.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#in", dateTimePicker2.Value);
cmd.Parameters.AddWithValue("#out", dateTimePicker3.Value);
int value = cmd.ExecuteNonQuery();
}
}
Additionally, use using statements to automatically close and clean up database resources.

C# Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

Apologies in advance if I missed an answer to this somewhere but I wasn't quite finding it anywhere. So I'm building an application that scans PDF's of service orders our company gets, parses it, and inserts it into a SQL DB. The problem is at the end of this code. It successfully :
saves the original pdf in the proper folder
scans the pdf and parses it
inserts the correct data into the service order table
grabs PK of service order just created as we need that for the next batch of inserts
Here is where it gets hung up with a Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
I foreach through all the instruments as there are multiples per Service Order, but it is erroring on this somewhere. to be clear I put a break point on the insert statement and all of the data is good and in the proper format ("string" int)
I feel like its in my connection maybe?
Anyways, thanks in advance for the help.
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/PDF/") + filename);
// Now we parse the PDF by creating a new ServiceOrder object and parsing from it.
ServiceOrder so = new ServiceOrder();
// Make sure we load the PDF from the correct path on the server
so.LoadPDF(Server.MapPath("~/PDF/") + filename);
String strConnString = "Data Source=127.0.0.0;Initial Catalog=SOMECATALOG;User ID=SOMEUSER;Password=SOMEPASSWORD";
// Insert Into Service Orders Table
string defaultdate = DateTime.Now.ToString("yyyy-MM-dd");
String strQuery = "insert into TServiceOrders (strServiceOrderNo, intStatusCodeID, strCustomerName, strCustomerNo, strCustomerAddress1, strCustomerAddress2, strCustomerAddress3, intRepID, strServiceDescription, strServiceRequestDate, strServiceOrderDate, strNotes) values ('"
+ so.ServiceOrderNumber.ToString() + "', 2, '"
+ so.CustomerContactName.ToString() + "', '"
+ so.CustomerNumber.ToString() + "', '"
+ so.CustomerContactAddress1.ToString() + "', '"
+ so.CustomerContactAddress2.ToString() + "', '"
+ so.CustomerContactAddress3.ToString() + "', 1, '', '"
+ defaultdate + "', '" + defaultdate + "', '')";
SqlConnection conn = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand(strQuery, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
// Grabbing latest primary key od service order just added for next instrument inserts
int lastid = 999999;
String strPKquery = "select top 1 intServiceOrderID from TServiceOrders order by intServiceOrderID desc";
SqlDataReader rdr = null;
SqlConnection conn2 = new SqlConnection(strConnString);
SqlCommand cmd2 = new SqlCommand(strPKquery, conn2);
try
{
conn2.Open();
rdr = cmd2.ExecuteReader();
while (rdr.Read())
{
lastid = (int)rdr["intServiceOrderID"];
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn2 != null)
{
conn2.Close();
}
}
// Insert Into Service Instruments Tables
SqlConnection conn3 = new SqlConnection(strConnString);
conn3.Open();
foreach (ServiceInstrument sin in so.ServiceInstruments)
{
string sim = "";
sim = sin.ServiceInstrumentModel;
if (String.IsNullOrEmpty(sim))
{
sim = "";
}
else
{
sim = sin.ServiceInstrumentModel.ToString();
}
string sid = "";
sid = sin.ServiceInstrumentDescription;
if (String.IsNullOrEmpty(sid))
{
sid = "";
}
else
{
sid = sin.ServiceInstrumentDescription.ToString();
}
string sis = "";
sis = sin.ServiceInstrumentSerial;
if (String.IsNullOrEmpty(sis))
{
sis = "";
}
else
{
sis = sin.ServiceInstrumentSerial.ToString();
}
string sih = "";
sih = sin.ServiceInstrumentHandle;
if (String.IsNullOrEmpty(sih))
{
sih = "";
}
else
{
sih = sin.ServiceInstrumentHandle.ToString();
}
string sip = "";
sip = sin.ServiceInstrumentParentAsset;
if (String.IsNullOrEmpty(sip))
{
sip = "";
}
else
{
sip = sin.ServiceInstrumentParentAsset.ToString();
}
String strQuery3 = "insert into TServiceInstruments values ('" + sim.ToString() + "', '" + sid.ToString() + "', '" + sis.ToString() + "', '" + sih.ToString() + "', " + sip.ToString() + ", " + lastid + ")";
SqlCommand cmd3 = new SqlCommand(strQuery3, conn3);
cmd3.ExecuteNonQuery();
}
conn3.Close();
When writing insert statements you should always specify the column names. This will protect the code from changes in the order of the columns in the table schema.
You are not using parameters in your sql statements, this leaves your code vulnerable to Sql Injection.
You should use using statements around your SqlConnection instances to ensure they are closed even when an Exception occurs.
Your logic is very difficult to follow, split your code until methods with meaningful names instead of having 1 "God" method that does everything.
If you follow those guidelines the problem will most likely solve itself in your refactoring.
Update Code Fragment
Note that you should always specify the correct types for your columns and the length if applicable. Also pass the actual value and never the string value.
const String strQuery3 = "INSERT INTO TServiceInstruments (sim, sid, sis, sih, sip, lid) VALUES (#sim, #sid, #sis, #sih, #sip, #lid)";
using(var conection = new SqlConnection(strConnString))
using(SqlCommand command = new SqlCommand(strQuery3, connection))
{
command.Parameters.Add(new SqlParameter("#sim", SqlDbType.VarChar, 200){Value = sim});
command.Parameters.Add(new SqlParameter("#sid", SqlDbType.VarChar, 200){Value = sid});
command.Parameters.Add(new SqlParameter("#sis", SqlDbType.VarChar, 200){Value = sis});
command.Parameters.Add(new SqlParameter("#sih", SqlDbType.VarChar, 200){Value = sih});
command.Parameters.Add(new SqlParameter("#sip", SqlDbType.Int){Value = sip});
command.Parameters.Add(new SqlParameter("#lid", SqlDbType.Int){Value = lid});
connection.Open();
command.ExecuteNonQuery();
}
Final note: You really need to learn how to read Exceptions and this includes the Stack Trace which points directly to the line in the call stack where the Exception originated. If you can understand this then debugging becomes much easier.
Maybe this doesn't deserve to be an answer, but I'm trying to build some reputation, so here goes :).
I suspect that your error lies in the "insert into TServiceInstruments ..." statement. Namely, you are giving the table more (or less) columns. As a good practice, always specify the columns, like this:
insert into TServiceInstruments (column1, column2, column3)
values (1, 2, 3)

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();
}
}

Error connecting to MS Access database from C# Winform

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

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