This should be really simple. Basically I'm just inserting data into the table:
string sql = "insert into Files(filename, filedate, filedata, filesize) values(xname, xdate, xdata, xsize);select last_insert_id() as lastid from Files";
The values specified here (xname, xdate, etc) are just parameters and I'm setting their values before executing the query.
Unfortunately, something's gone wrong and I'm getting the following error:
Unknown column 'xname' in 'field list'
I can understand that for some or other reason, it's looking for a column named "xname" which, obviously doesn't exist. What I can't understand is why it's doing this.
Typically I "tag" parameters with the # symbol (#name, #date, etc) which generally works, but I'm working on a system written by another developer in the company and I have to maintain conventions.
Can anyone explain why I'm getting this error?
If xname, xdate, xdata and xsize are variables, then you could do something like:
string sql = "insert into Files(filename, filedate, filedata, filesize) values(" +
xname + ", " + xdate + ", " +
xdata + ", " + xsize +
");select last_insert_id() as lastid from Files";
Related
I have a query to insert a row into a table, which has a field called ID, which is populated using an AUTO_INCREMENT on the column. I need to get this value for the next bit of functionality, but when I run the following, it always returns 0 even though the actual value is not 0:
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ")";
int id = Convert.ToInt32(comm.ExecuteScalar());
According to my understanding, this should return the ID column, but it just returns 0 every time. Any ideas?
EDIT:
When I run:
"INSERT INTO INVOICE (INVOICE_DATE, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, CUSTOMER_ID) VALUES ('2009:01:01 10:21:12', 50, 7, 57, 2134);last_insert_id();"
I get:
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'last_insert_id()' at line 1"}
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertStatement; // Set the insert statement
comm.ExecuteNonQuery(); // Execute the command
long id = comm.LastInsertedId; // Get the ID of the inserted item
[Edit: added "select" before references to last_insert_id()]
What about running "select last_insert_id();" after your insert?
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', "
+ bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ");";
+ "select last_insert_id();"
int id = Convert.ToInt32(comm.ExecuteScalar());
Edit: As duffymo mentioned, you really would be well served using parameterized queries like this.
Edit: Until you switch over to a parameterized version, you might find peace with string.Format:
comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();",
insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID);
Use LastInsertedId.
View my suggestion with example here: http://livshitz.wordpress.com/2011/10/28/returning-last-inserted-id-in-c-using-mysql-db-provider/
It bothers me to see anybody taking a Date and storing it in a database as a String. Why not have the column type reflect reality?
I'm also surprised to see a SQL query being built up using string concatenation. I'm a Java developer, and I don't know C# at all, but I'd wonder if there wasn't a binding mechanism along the lines of java.sql.PreparedStatement somewhere in the library? It's recommended for guarding against SQL injection attacks. Another benefit is possible performance benefits, because the SQL can be parsed, verified, cached once, and reused.
Actually, the ExecuteScalar method returns the first column of the first row of the DataSet being returned. In your case, you're only doing an Insert, you're not actually querying any data. You need to query the scope_identity() after you're insert (that's the syntax for SQL Server) and then you'll have your answer. See here:
Linkage
EDIT: As Michael Haren pointed out, you mentioned in your tag you're using MySql, use last_insert_id(); instead of scope_identity();
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\Users\\SS\\Documents\\131Current1\\125\\Current one\\ClinicMainDatabase.accdb");
my_con.Open();
OleDbCommand o_cmd1 = my_con.CreateCommand();
o_cmd1.CommandText = "INSERT INTO Personal_Details(Date,Time,Patient_Name,Contact_Number,Gender,Allergic_To,KCO) VALUES ('" + DateTime.Now.ToString("dd-MM-yyyy") + "','" + DateTime.Now.ToString("h:mm:ss tt") + "','" + txtPatientName.Text + "','" + txtContactNo.Text + "','" + comboBoxGender.Text + "','" + txtAllergic.Text + "','" + txtKCO.Text + "')";
int j = o_cmd1.ExecuteNonQuery();
I am getting the Syntax error in Insert Statement I don't understand what is mistake if any one help me I am really thank full.Thanks in Advance.
Date and Time are typically reserved keywords in many database systems. You should at the very least wrap them with [ ]. More preferably, if you are designing the table, change the field name to something more descriptive. For example if the Date and Time represented a reminder then you could use ReminderDate and ReminderTime so as not to interfere with reserved keywords.
And follow the parameter advice that's already been given.
Use command parameters instead of concatenating strings. Your code is open for SQL Injection attacks or in your specific case the problem may be related with invalid user input. Try to thing about this situation:
What if the txtContactNo.Text returns this string "Peter's contact is +123456" ? How does the SQL query will look then? Pay close attention to ' character.
You should ALWAYS use parametrized SQL queries no matter how good you thing your input validation is. It also has more advantages like query plan caching etc.
So in your case the code must be written like this:
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\Users\\SS\\Documents\\131Current1\\125\\Current one\\ClinicMainDatabase.accdb");
using(my_con)
{
my_con.Open();
using(OleDbCommand o_cmd1 = my_con.CreateCommand())
{
o_cmd1.CommandText = #"
INSERT INTO Personal_Details ([Date], [Time], Patient_Name, Contact_Number, Gender, Allergic_To, KCO)
VALUES (#date, #time, #name, #contNo, #gender, #alergic, #kco)";
o_cmd1.Parameters.AddWithValue("#date", DateTime.Now.ToString("dd-MM-yyyy"));
o_cmd1.Parameters.AddWithValue("#time", DateTime.Now.ToString("h:mm:ss tt"));
o_cmd1.Parameters.AddWithValue("#name", txtPatientName.Text);
o_cmd1.Parameters.AddWithValue("#contNo", txtContactNo.Text);
o_cmd1.Parameters.AddWithValue("#gender", comboBoxGender.Text);
o_cmd1.Parameters.AddWithValue("#alergic", txtAllergic.Text);
o_cmd1.Parameters.AddWithValue("#kco", txtKCO.Text);
o_cmd1.ExecuteNonQuery();
}
}
Also make sure that you are properly disposing the connection and the command objects (by using :) the using keyword)
For more info read the docs in MSDN
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
Is there a way to store TEXT in SQLite database without SQLite trying to parse it?
Ran into a problem where when you store TEXT that is similar to SQLite query, it tries to parse it for some reason.
Query I use to save TEXT: "insert into tableName (Name, DateCreated, Reminder, Content) values ('name', 'currentDate', 'reminder', 'content')".
Similar text I'm trying to save: "SELECT NAME FROM sqlite_master WHERE TYPE='table' ORDER BY NAME".
When i try to save something like that, it says: Error: SQL logic error or missing database near "table":syntax error
Please note that values (name, currentDate, reminder, content) are not hard coded, they are passed as strings. actual code is like below:
SQLiteCommand command = new SQLiteCommand("insert into " + cateName + " (Name, DateCreated, Reminder, Content) values ('" + noteName + "', '" + currentDate + "', '" + reminder + "', '" + content + "')", connection);
Thanks for any input.
As I suspect, the problem is that you're putting your values directly into the SQL - without even trying to escape them. Don't do that. As well as the problems you're seeing, you've opened yourself up to a SQL injection attack. Use parameterized SQL instead, and specify values for the parameters.
For example:
// It's not clear what cateName is, but I'll assume *that* bit is valid...
string sql = new SQLiteCommand("insert into " + cateName +
" (Name, DateCreated, Reminder, Content) values " +
"(#Name, #DateCreated, #Reminder, #Content)");
using (var command = new SQLiteCommand(sql, connection))
{
command.Parameters.Add("#Name", SQLiteType.Text).Value = noteName;
command.Parameters.Add("#DateCreated", SQLiteType.DateTime).Value = currentDate;
command.Parameters.Add("#Reminder", SQLiteType.Text).Value = reminder;
command.Parameters.Add("#Content", SQLiteType.Text).Value = content;
command.ExecuteNonQuery();
}
I've got a error which I can't understand. When I'm debugging and trying to run a insert statement, its throwing the following exception:
"There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement."
I have looked all over my code, and I can't find the mistake I've made.
This is the query and the surrounding code:
SqlConnection myCon = DBcon.getInstance().conn();
int id = gm.GetID("SELECT ListID from Indkøbsliste");
id++;
Console.WriteLine("LNr: " + listnr);
string streg = GetStregkode(navne);
Console.WriteLine("stregk :" + strege);
string navn = GetVareNavn(strege);
Console.WriteLine("navn :" + navne);
myCon.Open();
string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values(" + id + "," + listnr + ", '" + strege + "','" + navn + "'," + il.Antal + ", "+il.Pris+")";
Console.WriteLine(il.Antal+" Antal");
Console.WriteLine(il.Pris+" Pris");
Console.WriteLine(id + " ID");
SqlCommand com = new SqlCommand(query, myCon);
com.ExecuteNonQuery();
com.Dispose();
myCon.Close();
First of all check the connection string and confirm the database location and number of columns a table has.
Suggestion : Do not use hardcoded SQL string. Use parameterized sql statements or stored-proc.
Try parameterized way,
string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris)
Values (#ListID, #ListeNr, #Stregkode, #Navn, #Antal, #Pris)"
SqlCommand com = new SqlCommand(query, myCon);
com.Parameters.Add("#ListID",System.Data.SqlDbType.Int).Value=id;
com.Parameters.Add("#ListeNr",System.Data.SqlDbType.Int).Value=listnr;
com.Parameters.Add("#Stregkode",System.Data.SqlDbType.VarChar).Value=strege ;
com.Parameters.Add("#Navn",System.Data.SqlDbType.VarChar).Value=navn ;
com.Parameters.Add("#Antal",System.Data.SqlDbType.Int).Value=il.Antal;
com.Parameters.Add("#Pris",System.Data.SqlDbType.Int).Value=il.Pris;
com.ExecuteNonQuery();
Please always use parametrized queries. This helps with errors like the one you have, and far more important protects against SQL injection (google the term, or check this blog entry - as an example).
For example, what are the actual values of strege and/or navn. Depending on that it may render your SQL statement syntactically invalid or do something worse.
It (looks like) a little more work in the beginning, but will pay off big time in the end.
Are you using danish culture settings?
In that case if il.Pris is a double or decimal it will be printed using comma, which means that your sql will have an extra comma.
Ie:
INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values(33,5566, 'stegkode','somename',4, 99,44)
where 99,44 is the price.
The solution is to use parameters instead of using the values directly in you sql. See some of the other answers already explaining this.
I have web search form, When i submit my search in the search box,
The result are returned but with contains % in the file name.
for example. the original file name is abc.jpeg, so the result returned will be a%bc.
or if a folder is found with, so its the same for the folder name.
if a folder name is jack, in the result it will be ja%ck.
I have the text box (as a search box, and i have set the value of the search text box as) <%search text%>
Thanks for the help and taking time to read it.
I am using Asp.net, C# and Access DB.
code :
iscBuilder.AddSelect("* ");
iscBuilder.AddFrom("[table1] ");
iscBuilder.AddWhereClause("( column_name like('%" + pQuery + "%') or column_name like('%" + pQuery + "%') or column_name like('" + pQuery + "%') or column_name like('" + pQuery + "%') )");
iscBuilder.AddWhereClause("(column_name like( '" + path + "') or column_name like( '" + path + "')) order by column_name");
OleDbConnection sqlconConnection = (OleDbConnection)DatabaseConnection.Instance.GetConnection();
OleDbCommand sqlcmdCommand1 = new OleDbCommand(iscBuilder.ToString(), sqlconConnection);
sqlcmdCommand1.CommandType = CommandType.Text;
This is how i call the function: public XmlDocument GetSearchResults(string pQuery, string path,int from , int to)
{
List <T> ts= T.GetF().Getresult(pQuery, path);
return createXMLThumnails(thmbNails,from , to);
}
Have nice day
Try using a parameterised query or stored procedure to get your data - all this joining strings to make SQL statements is very fiddly and problematic.
Have a look at using Parameterised Queries or Stored Procedures.