Syntax Error Ocurring on the Data Reader - c#

try
{
int i = 0;
using (SqlConnection sqlCon = new SqlConnection(Form1.connectionString))
{
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
// MessageBox.Show(commandString);
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
i = 1;
if (i == 0)
{
MessageBox.Show("Error in Logging In!", "Error");
}
MessageBox.Show("Successfully Logged In");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I'm making a LoginForm for a Project.I have created a table which shows the LoginDetails(Account,ID,LoginTime,LogoutTime).But when I run the Program,it doesn't runs successfully.I face an error which is in Pic-2.When I remove sql 'data reader',the program runs without displaying the error.

When you concatenate a null it basically adds nothing to the string, so this code:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
results of this string, and as you can see it has an extra comma, that causes the exception:
"INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('acc',textbxID,, SYSDATETIME());"
If you want to add NULL to the query it has to be a string, so do this instead:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID + ", NULL , SYSDATETIME()" + ");";
And you are using ExecuteReader instead of ExecuteNonQuery. You cannot use ExecuteReader for inserting rows to the DB.
Also, as someone mentioned in the other answer, you better do it with parametes to avoid SQL Injections.

Related

Error in C# insert statement for SQL Server

I am trying to pass an insert statement in a C# Winforms to SQL Server. I keep getting a syntax error that just doesn't make sense to me
error in syntax near "("
My syntax is perfectly fine, as when I copy and paste into SQL Server Mgmt Studio, the code runs perfectly.
Any help would be greatly appreciated!
Thanks!
try
{
using (var cmd = new SqlCommand("INSERT INTO " + intodrop.SelectedText + "(" + colnamedrop.SelectedText.ToString() + "," +
colnamedrop2.SelectedText.ToString() + ") " + "VALUES" + " (" + valuebox.Text + ");"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#tbl", intodrop.SelectedText);
cmd.Parameters.AddWithValue("#colname", colnamedrop.SelectedText);
cmd.Parameters.AddWithValue("#values", valuebox.Text);
cmd.Parameters.AddWithValue("#colname2", colnamedrop2.SelectedText);
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}
Check if SelectedText property returns right values. Try to use Text property instead.
var cmd = new SqlCommand("INSERT INTO " + intodrop.Text +
"(" + colnamedrop.Text + ',' + colnamedrop2.Text + ") "
+ "VALUES" + " (" + valuebox.Text + ");")
You missed comma between column names when insert sql statement preparing. When printing you have comma and display correctly.
Concatenated sql statement without any inputs validation is widely open for sql injection attacks. Try to use parameter as much as possible.
It looks like you are trying to insert values to two columns, but you are appending them like this "Col1+Col2", instead of "Col1+','+Col2".
using (var cmd = new SqlCommand("INSERT INTO " + intodrop.SelectedText + "(" + colnamedrop.SelectedText.ToString() + ','+
colnamedrop2.SelectedText.ToString() + ") " + "VALUES" + " (" + valuebox.Text + ");"))
I hope this resolves the issue.
First try hard coding your insert value after that change it based on your need. Confirm the column data types are assigned correctly.
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Property ( FolioNo,PropertyType) VALUES (001,'WIP')"))
{
cmd.Connection = con;
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}
1) You should have two texbox for entering your values. If no column names you gray the value of column 1, ditto for column 2.
This allows you not to have to enter quote (do not forget to make an escape quotes
2) use the string.format function for more readability
try
{
//Add columns selected
List<string> Mycolumns = new List<string>();
If (! string.IsNullOrEmpty(colnamedrop.Text)) Mycolumns.Add(colnamedrop.Text);
If (! string.IsNullOrEmpty(colnamedrop2.Text)) Mycolumns.Add(colnamedrop2.Text);
//Add values selected with escaped quoted and string quoted
List<string> Myvalues ​​= new List<string>();
If (! string.IsNullOrEmpty(colvalue1.Text)) Myvalues.Add("'" + colvalue1.Text.Replace("'", "''") + "'");
If (! string.IsNullOrEmpty(colvalue2.Text)) Myvalues.Add("'" + colvalue2.Text.Replace("'", "''") + "'");
//If nothing selected, no action
if (Mycolumns.Count==0 && Myvalues.Count==0) return;
//Build query
String Query = string.Format ( "INSERT INTO {0} ({1}) VALUES ({2})", intodrop.Text, string.Join(Mycolumns, ", "), string.Join(Myvalues, ", "));
//Execute query
using (var cmd = new SqlCommand(Query, con ))
{
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
con.Close();
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}

Problems storing key in MS SQL db with C# Code

To get more familiar with both c# and ms sql, I made a key generator which is working good. But I want to store they key at a database so I made a method that runs a query and it should store the key(I thought)
This is my method:
public SqlDataReader InsertInto(string tableName, string[] values)
{
string query = "";
try
{
query = "INSERT INTO " + tableName + " VALUES('" + values[0] + "')";
for (int i = 1; i < values.Length; ++i)
query += ", '" + values[i] + "'";
query += ")";
}
catch
{
// ignored
}
return ExecuteQuery(query);
}
And this is the code where I execute my query:
private SqlDataReader ExecuteQuery(string query)
{
SqlConnection connection = null;
SqlDataReader dataReader = null;
try
{
using (connection = new SqlConnection(Hash.RunDecryption()))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
using (dataReader = command.ExecuteReader())
{
}
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Failed to execute data! " + ex.Message, "Error!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
dataReader?.Close();
CloseConnection(connection);
}
finally
{
dataReader?.Close();
CloseConnection(connection);
}
return dataReader;
}
And the query that is being generated is this INSERT INTO Keys VALUES('fap0zkxbvw3')
But I get the following error:
Failed to execute data! Incorrect syntax near ')'.
The immediate problem is that you have 1 too many closing brackets:
query = "INSERT INTO " + tableName + " VALUES('" + values[0] + "')";
should be
query = "INSERT INTO " + tableName + " VALUES('" + values[0] + "'";
But you should really look into properly constructing your queries, using parameterizations, stored procedures, etc.

sql missing comma

protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ("+ ID + "," + password + "," + name + "," + position + "," + accessRight + "," + status + "," + createOn + "," +loginID+ ")";
readdata.updateData(sqlcommand);
}
I am passing the sqlcommand to readdata class for execute..and its throw me this error..
ORA-00917: missing comma
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: ORA-00917:
missing comma.
The readdata class function code as below.
public void updateData(string SqlCommand)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
OleDbCommand cmd = new OleDbCommand(SqlCommand, conn);
OleDbDataAdapter daPerson = new OleDbDataAdapter(cmd);
conn.Open();
cmd.ExecuteNonQuery();
}
Given that most of your columns are variable-length character, they must be enclosed in single quotes.
So, instead of:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES (" + InputValue + ")";
You would, at minimum, need this:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES ('" + InputValue + "')";
The result of the first statement, for an InputValue of "foo", would be:
INSERT INTO myTable (ColumnName) VALUES (foo)
which would result in a syntax error.
The second statement would be formatted correctly, as:
INSERT INTO myTable (ColumnName) VALUES ('foo')
Additionally, this code seems to be using values entered directly by the user, into txtID, txtPassword, and so on. This is a SQL Injection attack vector. Your input needs to be escaped. Ideally, you should use parameterized queries here.
This appears to be c#. Please update your tags accordingly.
At any rate, if it is .Net, here is some more information about parameterizing your queries:
OleDbCommand.Parameters Property
OleDbParameter Class
Try this
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ('"+ ID + "','" + password + "','" + name + "','" + position + "','" + accessRight + "','" + status + "','" + createOn + "','" +loginID+ "')";
Concatenating the query and executing it is not reccomended as it may cause strong SQl Injection. Suppose if any one of those parameters contain a comma(,) like USERPWD=passwo',rd then query will devide it as passwo and rd by the comma. This may be a problem
It is recommended that you use "Parameterized queries to prevent SQL Injection Attacks in SQL Server" and hope it will resolve your issue.
Your code can be rewritten as follows
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string strQuery;
OleDbCommand cmd;
strQuery = "INSERT INTO USERMASTER(USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES(#ID,#password,#name,#position,#accessRight,#status,#createOn,#loginID)";
cmd = new OleDbCommand(strQuery);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#position", position);
cmd.Parameters.AddWithValue("#accessRight", accessRight);
cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters.AddWithValue("#createOn", createOn);
cmd.Parameters.AddWithValue("#loginID", loginID);
bool isInserted = readdata.updateData(cmd);
}
rewrite your updateData data as follows
private Boolean updateData(OleDbCommand cmd)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}

Error while using MySqlTransaction for multiple inserts

I have a form in windows where I am doing insert statement for header and detail.
I am using MySqlTransaction for the form. When there is no error in header and detail the transaction gets committed but when there is an error in insert query of detail then the following error comes while rollback
There is already an open DataReader associated with this Connection
which must be closed first.
Here is my code.
public string Insert_Hardening_Measures_HdrANDDtl(BL_Vessel_Hardening_Measures objHdr, List<BL_Vessel_Hardening_Measures> objDtl)
{
string success = "true";
string success1 = "";
MySqlConnection MySqlConnection1 = new MySqlConnection(strCon);
MySqlConnection1.Open();
MySqlTransaction MyTransaction = MySqlConnection1.BeginTransaction();
MySqlCommand MyCommand = new MySqlCommand();
MyCommand.Transaction = MyTransaction;
MyCommand.Connection = MySqlConnection1;
try
{
MyCommand.CommandText = "insert into hardening_measures_hdr (Hardening_Measures_Hdr_id,Month,Year) values (" + objHdr.Hardening_Measures_Hdr_id + ",'" + objHdr.Month + "','" + objHdr.Year + "')";
MyCommand.ExecuteNonQuery();
for (int i = 0; i < objDtl.Count; i++)
{
MyCommand.CommandText = "insert into hardening_measures_dtl (Hardening_Measures_Dtl_id,Hardening_Measures_Hdr_id,Hardening_Measures_Mst_id,Value) values (" + objDtl[i].Hardening_Measures_Dtl_id + "," + objDtl[i].Hardening_Measures_Hdr_id + ",'" + objDtl[i].Hardening_Measures_Mst_id + ",'" + objDtl[i].Value + "')";
MyCommand.ExecuteNonQuery();
}
MyTransaction.Commit();
MySqlConnection1.Close();
}
catch
{
MyTransaction.Rollback();
}
return success;
}
Anybody who have come through this kind of problem please suggest something

OLEDB insert rows into a replaced table

I'm trying to replace the table in Excel 2007 using OLEDB.
Firstly I'm executing the command "Drop Table", than "Create Table" and it works fine.
But if I now want to insert data ("INSERT INTO") into this table, it fails. There are no errors or exceptions by OleDbCommand.ExecuteNonQuery(), transaction commits at the end succesffuly, the database is just empty.
Any ideas why?
connection.Open();
string access_com = "DROP TABLE " + globalPrefix + prefix + TableName;
OleDbCommand execute = new OleDbCommand(access_com, connection);
try
{
execute.ExecuteNonQuery();
}
catch (Exception ex)
{
ConfigDataSet.Log.AddLogRow("The program cannot drop table you want. Close the file with it and run program again!", 1);
return 1;
}
access_com = "CREATE TABLE [" + globalPrefix + prefix + TableName + "]" + fieldString + ")";// CONSTRAINT PK" + TableName + " PRIMARY KEY " + primaryKey + ")";
execute.CommandText = access_com;
execute.ExecuteNonQuery();
OleDbTransaction transaction = connection.BeginTransaction();
access_com = "INSERT INTO " + TableName + "( " + allfields + ")" + " VALUES (" + parametersString + ")";
OleDbCommand execute = new OleDbCommand(access_com, connection);
execute.Transaction = transaction;
try
{
execute.ExecuteNonQuery();
execute.Parameters.Clear();
}
catch (OleDbException ex)
{
ConfigDataSet.Log.AddLogRow("Inserting row failed: ", 2);
failedInsertions++;
}
You have the INSERT query in a transaction, but I don't see a commit anywhere in your code:
execute.ExecuteNonQuery();
transaction.Commit();
You should probably also have the transaction.Rollback(); in your exception block. See OleDbConnection.BeginTransaction Method

Categories