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();
}
}
Related
So my problem is that is says that there is my problem in my update statement, but I believe that my statement is right, if I am wrong please correct me
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "update Admin set Password='" + Npassword.Text + "' WHERE Pk='" + txt2.Text + "'";
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Password Changed");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error, fill the fields required" + ex);
connection.Close();
}
Ignoring for a moment the good advice in the comments, Password is a reserved word in Access SQL, thus must be bracketed:
string query = "update Admin set [Password]='" + Npassword.Text + "' WHERE Pk='" + txt2.Text + "'";
Also, if Pk is numeric, no quotes:
string query = "update Admin set [Password]='" + Npassword.Text + "' WHERE Pk=" + txt2.Text + "";
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)
When I click on this button, I face with this error:
executenonquery commandtext property has not been initialized
private void button_FirstStep_Click(object sender, EventArgs e)
{
SqlConnection Conn = new SqlConnection(Yahya.strcon);
Conn.Open();
int CurrentCount = Convert.ToInt32(label_CurrentCount.Text);
string strcom1 = "select * from vm1 where count = '" + (CurrentCount - 1) + "' and benchmarkid = '" + Structure.BenchmarkID + "' ";
SqlCommand cmd = new SqlCommand(strcom1, Conn);
SqlDataReader reader = cmd.ExecuteReader();
string strcom = "";
while (reader.Read())
{
if (reader["vmid"].ToString() != "")
{
string vmid = reader["vmid"].ToString();
strcom += "update vm1 set pmid = (select pmid from vm1 as VM2 where benchmarkid = '" + Structure.BenchmarkID + "' and vm2.count ='" + (CurrentCount - 1) + "' and vm2.vmid ='" + vmid + "' ) where count = '" + CurrentCount + "' and vmid = '" + vmid + "' and benchmarkid = '" + Structure.BenchmarkID + "' \n";
}
}//end of while
reader.Close();
cmd.CommandText = strcom;
cmd.ExecuteNonQuery();
}
Rene is quite right about his comment, looks like your reader.Read() returns false and that's why your code never goes into your while loop and your CommandText is assigned to "", that's why ExecuteNonQuery throws
ExecuteNonQuery: CommandText property has not been initialized
You can check your strcom is empty string or not to solve your problem but I see more wrong things in your code other than that..
Looks like your count column is numeric value but you supplied your CurrentCount - 1 as a character with single quotes. If it is not numeric, it should. Read: Bad habits to kick : choosing the wrong data type
Based on it's name, benchmarkid should(?) be numeric types as well.
You can solve this two problem with using parameterized queries because this kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connection, command and reader automatically instead of calling Close or Dispose methods manually.
Open your connection just before you execute your command.
You could solve this by simply debugging before asking.
The reason for this error is presumably that your first request returns zero results.
So reader.Read() is always false and strcom stays empty. You set an empty string as cmd.CommandText before the call to ExecuteNonQuery().
To solve this, simply check if the string is empty and execute the last query only if it is not empty:
...
reader.Close();
if (!string.IsNullOrEmpty(strcom))
{
cmd.CommandText = strcom;
cmd.ExecuteNonQuery();
}
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
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 + "'";