I am trying to Insert a record in MS Access DB using OLEDB in windows application.
I am getting an error "missing semicolon at end of sql statement" there is no syntax error in sql insert statment.
My code
This is the insert statement i am using:
INSERT INTO Student
VALUES ('SRI-10-101','001','guru','30/05/2010 12:00:00 AM','','','','','','','600028','','','','','','','30/05/2010 11:25:44 AM','');
along with the code:
conn = this.GetConnection();// which returns Connection object
tran = conn.BeginTransaction();
OleDbCommand cmd = conn.CreateCommand();
cmd.Connection = conn;
cmd.CommandText = strQuery;// Insert statement
cmd.CommandType = CommandType.Text;
cmd.Transaction = tran;
cmd.ExecuteNonQuery();
tran.Commit();
I tried with semicolon also still i get error;
Thanks
It looks like you want to set your strQuery to the value of your insert statement.
Based on your code it should look something like this:
string strQuery = "INSERT INTO Student
VALUES ('SRI-10-101','001','guru','30/05/2010 12:00:00 AM','','','','','','','600028','','','','','','','30/05/2010 11:25:44 AM','')";
As always you should verify that you are connected and defaulted to the proper database (or specify it explicitly prior to your table name (i.e. MyAwesomeDatabase.dbo.Student).
Finally it also looks like you are trying to insert a number as a character array ('001' or '600028'), if the fields in your database are of a numeric type then SQL prefers numbers without quote delimiters.
Good luck!
Related
I have a sql table that saves a word and I need to check if that word already exists and I so, I should get a message saying that word already exists.
Is it possible? If so how should I do it?
I will leave it down below myccode to add the word for the sql, but if you need something else I will provide you without any problem.
string conn = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
using (SqlConnection sqlConn = new SqlConnection(conn))
{
sqlConn.Open();
string sqlQuery = #"INSERT INTO testetiposdestados(CDU_ESTADOS) VALUES(#estados)";
SqlCommand SQLcm = new SqlCommand();
SQLcm.Connection = sqlConn;
SQLcm.CommandText = sqlQuery;
SQLcm.CommandType = CommandType.Text;
SQLcm.Parameters.AddWithValue("#estados", textBox1.Text);
SQLcm.ExecuteNonQuery();
sqlConn.Close();
}
I'm using c#
You can use IF NOT EXIST statment like so
IF NOT EXISTS (SELECT * FROM testetiposdestados
WHERE CDU_ESTADOS = #estados)
BEGIN
INSERT INTO testetiposdestados(CDU_ESTADOS) VALUES(#estados)
END
Your query will become:
string sqlQuery =
#"IF NOT EXISTS(SELECT *
FROM testetiposdestados
WHERE CDU_ESTADOS = #estados)
BEGIN
INSERT INTO testetiposdestados(CDU_ESTADOS)
VALUES (#estados)
END";
If it inserted successfully it means it was not present in the table already.
I would recommend using a unique constraint:
CREATE UNIQUE CONSTRAINT unq_testetiposdestados_estados
UNIQUE (CDU_ESTADOS);
INSERT INTO testetiposdestados(CDU_ESTADOS)
VALUES(#estados);
This has the advantage that the database ensures that the value is unique, not the application. Hence, this will prevent another INSERT or UPDATE statement from producing a unique value.
Furthermore, this is much safer than the IF approach. That approach is subject to race conditions -- two threads attempting to insert the same value may both succeed.
I want to populate a table in mssql with the values entered by the user (the error comes from the NumericUpDown) and I'm using this code:
string cs= "Data Source=CODRINMA\\CODRINMA;Initial Catalog=BusManager; Trusted_Connection=True;";
string insert = "INSERT INTO TipAutocar ([IDTipAutocar], [Marca], [Model], [Nrlocuri] values ([#TipAutocar], [#Marca], [#Model], [#Nrlocuri]))";
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("#IDTipAutocar", txtID.Text);
cmd.Parameters.AddWithValue("#Marca", txtMarca.Text);
cmd.Parameters.AddWithValue("#Model", txtModel.Text);
cmd.Parameters.AddWithValue("#Nrlocuri", nmrLocuri.Value);
int valoare = cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(valoare + "Tipul de autocar a fost adaugat cu succes!", "BusManager");
}
}
catch (Exception er) { MessageBox.Show(er.Message); }
But, when I press button to insert, I'm having the following error and I can't figure it out what's to do:
Incorect syntax near the keyword 'values'.
I'm missing a closing round parenthesis before values here:
string insert = "INSERT INTO TipAutocar ([IDTipAutocar], [Marca], [Model], [Nrlocuri] values ([#IDTipAutocar], [#Marca], [#Model], [#Nrlocuri]))";
You are not allowed to use [] around the parameters, otherwise it's not a parameter and you'll get an error f.e. "invalid columnname [#TipAutocar]".
You also name the parameter #TipAutocar but you add it as IDTipAutocar.
Also, always use the correct type, all the more if you use AddWithValue which infers the type from the value. So i guess that IDTipAutocar is an int, then parse it to one before:
cmd.Parameters.AddWithValue("#IDTipAutocar", int.Parse(txtID.Text));
As an aside, i'm always using a verbatim string literal. On that way i can format my sql query as i want, even with multiple lines. This should work as exptected:
string insert = #"INSERT INTO TipAutocar
( IDTipAutocar, Marca, Model, Nrlocuri )
VALUES
( #IDTipAutocar, #Marca, #Model, #Nrlocuri)";
Look at this bracket;
string insert = "INSERT INTO TipAutocar ([IDTipAutocar], [Marca], [Model], [Nrlocuri] values (#TipAutocar, [#Marca, #Model, #Nrlocuri))";
^^^
You close it at the end of your query, you should close it just before your VALUES part.
Change it to;
string insert = "INSERT INTO TipAutocar ([IDTipAutocar], [Marca], [Model], [Nrlocuri]) values (#TipAutocar, #Marca, #Model, #Nrlocuri)";
^^^ ^^^
You don't need are not allowed to use square brackets for your parameters by the way. Also use using statement to dispose your SqlCommand as well. And since you used this statement for your SqlConnection, you don't need to close it with con.Close() because this statement do that automaticaly.
Also you define your parameter name as #TipAutocar in your command but try to add parameter name as #IDTipAutocar which does not match. Change your parameter name like;
cmd.Parameters.AddWithValue("#TipAutocar", txtID.Text);
And don't use AddWithValue anymore. It may generate unexpected results. Use .Add() method overloads instead to specify your SqlDbType and parameter size.
So I am trying to fetch a value from the database, selecting the row using WHERE INT.
conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=#tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#tafel", tafel);
cmd.ExecuteNonQuery();
However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"
I tried fetching a other one in the same table that is a var char and it worked perfectly.
Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.
Thanks!
Put your field name table in backticks (table is a reserved word in MySQL) :
query = "SELECT * FROM `tables` WHERE `table` = #tafel";
As others said, table is a reserved word in MySQL. You need to use quote with it like
query = "SELECT * FROM tables WHERE `table` = #tafel";
However, the best solution is to change the name to a nonreserved word.
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM tables WHERE `table` = #tafel";
cmd.Parameters.AddWithValue("#tafel", tafel);
conn.Open();
cmd.ExecuteNonQuery();
}
By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.
If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.
Why do I get an exception when trying to truncate a MySQL table (using MySQL Connector/Net)? I am trying to give the table name with a parameter.
This is the code I'm executing:
var connectionString = "Server="+_server+";Uid="+_user+";Pwd="+_password+";Database="+_database+";";
try
{
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
const string sql = "TRUNCATE TABLE #tablename"; // also tried with TRUNCATE #tablename
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#tablename", "test");
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex.ToString());
}
And this is the execption:
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error
in your SQ L syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near ''test'' at line 1
When I try a select query, for example, then I don't have any problems. This runs fine and returns correct data:
conn.Open();
const string sql = "SELECT body FROM test WHERE id=#pid";
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#pid", 1);
cmd.ExecuteScalar();
conn.Close();
Parameters are used for query values, not object names like tables.
So this will not work for sure.
You need to set the table name in the command string by using string concatenation. You can avoid sql injection attacks by manually checking for weird characters in the table name (spaces, dashes, semicolons, etc..)
I've been playing around with this for a while now, and i can't seem to get it to work either. I can't find any documentation online, so i'm starting to think you may not be able to truncate with a parameter like you've tried.
However, is there really a need to prevent SQL injection on this command? Does the user enter the name of the table they want to truncate, and if so, they're just going to truncate a table which...is essentially what the command does anyway?
Here is the query:
string query = #"INSERT INTO session (PK_Id, user_id, login_time, machine_ip, machine_fingerprint)
VALUES (UUID(), #UId, #LogInTime, #MIp, #MFingerPrint);
";
Now I need this last inserted id back, which is a UUID generated by MySQL. As far as I read there is no select_last_insert_id() function for UUIDs!! And I read for php you could assign UUID() function first to a variable and then return that value. But how to go about that in C#?
Something like this, but not exactly:
string query = #"INSERT INTO session (PK_Id, user_id, login_time, machine_ip, machine_fingerprint)
VALUES (#UUID = SELECT UUID(), #UId, #LogInTime, #MIp, #MFingerPrint);
"; //how to do this here?
Here is more of my code:
string query = #"INSERT INTO session (PK_Id, user_id, login_time, machine_ip, machine_fingerprint)
VALUES (#UUID = SELECT UUID(), #UId, #LogInTime, #MIp, #MFingerPrint);
";
try
{
if (_conn.State != ConnectionState.Open)
_conn.Open();
MySqlCommand cmd = new MySqlCommand(query, _conn);
cmd.Parameters.AddWithValue("#UId", Utility.usr.Id);
cmd.Parameters.AddWithValue("#LogInTime", DateTime.Now);
cmd.Parameters.AddWithValue("#MIp", GetMachineIP());
cmd.Parameters.AddWithValue("#MFingerPrint", GetHardwareFingerPrint());
var s= Convert.ToString(cmd.ExecuteScalar()); //this returns an empty string :(
//I need to get it to any .NET data type, string, or Guid or byte[] or anything.
But I need this datatype of s to be used in another WHERE clause in a query like this:
string query = #"UPDATE session SET logout_time = #LogOutTime
WHERE user_id = #UId AND PK_Id = #SessionId";
try
{
if (_conn.State != ConnectionState.Open)
_conn.Open();
MySqlCommand cmd = new MySqlCommand(query, _conn);
cmd.Parameters.AddWithValue("#UId", Utility.usr.Id);
cmd.Parameters.AddWithValue("#SessionId", s);
cmd.Parameters.AddWithValue("#LogOutTime", DateTime.Now);
cmd.ExecuteScalar();
Here #"SessionId" is the UUID field in the same table. So basically, how can I get the MySQL varbinary field in C# so that I could use that type to update by specifying WHERE in another query?
In MySQL table the UUID field is varbinary (I hope to see some solution that is not another php link or that is not asking me to switch to char datatype in the database :) ).
Edit: The problem here is we have already added plenty of UUIDs generated by MySQL into the table, so I'm a bit apprehensive about changing MySQL UUID to .NET Guid. If that's the only workaround, I'll consider that. Just that this is the first time we needed the inserted UUID value back so that I can update in another query another point of time.
A sub question: Is .NET Guid exactly the same thing as MySQL UUID?
You can use the Guid type which is the MS implementation of UUID. You should be aware that when inserting data into the DB, you may need to convert the Guid to ByteArray if the MySQL driver isn't familiar with handling Guid's. See Store GUID in MySQL from C# for an example of this.
I think you can go ahead with your earlier implementation without having to rely on MS Guid, but I fear I am too late :)
string query = #"INSERT INTO session (PK_Id, user_id, login_time, machine_ip, machine_fingerprint)
VALUES (UUID(), #UId, #LogInTime, #MIp, #MFingerPrint);
SELECT PK_Id FROM session WHERE login_time=#LogInTime AND machine_fingerprint=#MFingerPrint; //or something similar which gives you the exact same id - UUID
";
try
{
if (_conn.State != ConnectionState.Open)
_conn.Open();
MySqlCommand cmd = new MySqlCommand(query, _conn);
cmd.Parameters.AddWithValue("#UId", Utility.usr.Id);
cmd.Parameters.AddWithValue("#LogInTime", DateTime.Now);
cmd.Parameters.AddWithValue("#MIp", GetMachineIP());
cmd.Parameters.AddWithValue("#MFingerPrint", GetHardwareFingerPrint());
MySqlDataReader r = cmd.ExecuteReader();
if (r.Read()) //ensure if it is read only once, else modify your `WHERE` clause accordingly
{
var s = (Guid)r[0];
}
//or even (Guid)cmd.ExecuteScalar() would work
Now you can query in update like this:
string query = #"UPDATE session SET logout_time = #LogOutTime
WHERE user_id = #UId AND PK_Id = #SessionId";
try
{
if (_conn.State != ConnectionState.Open)
_conn.Open();
MySqlCommand cmd = new MySqlCommand(query, _conn);
cmd.Parameters.AddWithValue("#UId", Utility.usr.Id);
cmd.Parameters.AddWithValue("#SessionId", s.ToByteArray());
cmd.Parameters.AddWithValue("#LogOutTime", DateTime.Now);
cmd.ExecuteNonQuery();
Note: Here I have converted the Guid variable s to byte array before querying. This is important, in WHERE clause, be it UPDATE or SELECT statements in query. I would ask you to move to binary field in MySQL table from varbinary.
Edit: If your table would grow dramatically large then inserting and selecting is a bad idea since SELECT query is an additional query being run. In that case #PinnyM's choice is better. I really do not think MySQL or any other database would have a default way to give back "custom" inserted ids which are not something database generated. So in short I advice you to not go for this..
Edit2: See this answer for getting binary value to .NET datatype. Sometimes casting do not work depending on MySQL .NET connector version..