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.
Related
I have an easy insert query, but visual studio return "Syntax error in INSERT INTO command", i copy+paste the exact same query in the db (access) and it work... Any help??
public void Create(string mail, string nickname, string password, string avatar)
{
OleDbConnection cn = new OleDbConnection(_connectionString);
OleDbCommand cmd = new OleDbCommand();
try
{
String PwdSHA256;
SHA256 mySHA256 = SHA256.Create();
byte[] hashValue = mySHA256.ComputeHash(Encoding.UTF8.GetBytes(password));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hashValue.Length; i++)
{
builder.Append(hashValue[i].ToString("x2"));
}
PwdSHA256 = builder.ToString();
cn.Open();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO utenti ([email],[nickname],[password],[avatar],[attivo]) " +
"VALUES ('" + mail + "', '" + nickname + "', '" + PwdSHA256 + "','', false)";
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Session["errore"] = ex;
System.Web.HttpContext.Current.Response.Redirect("ErrorPage.aspx");
this._errore = ex.Message;
}
finally
{
cmd = null;
cn.Close();
}
}
Using SQL queries directly in your code is not a good coding practice, use SQL procedures and pass the parameters to SQL.
And be clear, the error you are facing is an execution time error or a compilation.
Use dbo.Your_DB_Name.utenti or Your_DB_Name.utenti instead of utenti.
Wrap up your 'false'
Are you still using PwdSHA256 encryption
Maybe you should change
cmd.CommandText = "INSERT INTO utenti (email,nickname,password,avatar,attivo) " +
"VALUES ('" + mail + "', '" + nickname + "', '" + PwdSHA256 + "','', false)";
And make sure your column in database is same with your query
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.
To start i don't have access to the database, we hit a problem with our university account and waiting for it to be reset. How ever i do have code that is giving me some problems and frankly i'm not sure i have even gone about this in the right way.
I am only trying to make a simple test program that creates a table, populates it then reads it.
If this isn't enough information i am sorry i should of waited but its bugging me getting these little errors in the code before i even get to a point i can compile to test tomorrow.
Here is the code to create the table, there does not seem to be any errors in the code
static void buildTable()
{
try
{
string sqlBuild = "CREATE TABLE Item ("
+ "Item_ID VARCHAR2(1),"
+ "Item_Name VARCHAR2(16),"
+ "Price_Consumer VARCHAR(5)"
+ " ); ";
OracleCommand cmd = new OracleCommand(sqlBuild, con);
Connect();
cmd.ExecuteNonQuery();
Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Here is the code to populate the table and this is where i am getting errors.
static void populateTable()
{
string[,] items;
items = new string[5,3] { { "1", "Mozzarella", "9.99" }, { "2", "Peperoni", "12.99" }, { "3", "Meat Feast", "14.99" }, { "4", "Chicken Tikka", "12.99" }, { "5", "Spicy Vegetarian", "11.99" } };
try
{
OracleCommand cmd = new OracleCommand();
OracleDataReader r = cmd.ExecuteReader();
r.Read();
for (int i = 1; i < 6; i++)
{
for(int j = 1; j < 4; j++)
{
OracleCommand comd = new OracleCommand();
comd.Connection = con;
comd.CommandText = "insert into Item(Item_ID, Item_Name, Price_Consumer) values(" items[i, j].ToString() + ", " + items[i, j].ToString() + ", " + items[i, j].ToString() ");";
Connect();
comd.ExecuteNonQuery();
Close();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
the errors are on the items[i,j], it tells me it expects an " ; "
lastly this is what im near 100% will work as this i have done in the past, but i have never tried to use c# to create or populate a table.
static void itemList()
{
string s = "\n";
try
{
Connect();
OracleCommand cmd = new OracleCommand(sql, con);
OracleDataReader r = cmd.ExecuteReader();
r.Read();
while (r.Read())
{
s = s + r["Item_ID"].ToString() + ", " + r["Item_Name"].ToString() + ", " + "£" +r["Price_Consumer"].ToString();
}
Close();
Console.WriteLine(s);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
here is the addtional code that might be relevant
static void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=username;Password=password;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=host)(PORT=port))(CONNECT_DATA=(SERVICE_NAME=SID)))";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
static void Close()
{
con.Close();
con.Dispose();
}
Declarations
static OracleConnection con;
static string sql = "select * from Item";
Your internal loop is not needed. When you try to insert a row, you don't call the insert one time for each column, but you call the insert one time for each row
Another problem are your columns of type VARCHAR, this means that you need to insert strings there, but you don't do it correctly.
This could be solved putting single quotes around those string to be recognized as such by the database engine.
for (int i = 1; i < 6; i++)
{
comd.CommandText = #"insert into Item(Item_ID, Item_Name, Price_Consumer)
values('" + items[i, 0].ToString() + "', '" +
items[i, 1].ToString() + "', '" +
items[i, 2].ToString() '");";
However while this will work for your simple example, this is still wrong. You should never concatenate string to build an sql command. This leads to Sql Injection and to a parsing error if the value to insert contains a single quote.
The only correct way to do it is through a parameterized query as this
comd.CommandText = #"insert into Item(Item_ID, Item_Name, Price_Consumer)
values(:ID, :Name, :Price)";
comd.Parameters.AddWithValue(":ID", items[i, 0].ToString());
comd.Parameters.AddWithValue(":Name",items[i, 1].ToString());
comd.Parameters.AddWithValue(":Price",items[i, 2].ToString());
(As a side benefit, look at how the command is more understandable now)
This line is not well formatted and is missing two + symbols:
comd.CommandText = "insert into Item(Item_ID, Item_Name, Price_Consumer) values(" +
items[i, j].ToString() + ", " +
items[i, j].ToString() + ", " +
items[i, j].ToString() + ");";
If you split it in a similar way to the above then it is easier to spot the errors
You are missing a '+' sign here
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
Following query is not inserting value in database.
Code:
try
{
for (int i = 0; i < listViewSubject.Items.Count; i+=2)
{
string query = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES ('" + listViewSubject.Items[i] + "', '" + this.reg_id + "')";
dal.InsertUpdateDelete(query);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
From your question I understand the issue is error with converting to int.You have to convert subject ID to int before inserting.
Try
{
for (int i = 0; i < listViewSubject.Items.Count; i+=2)
{
string query = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES (" + Int.Parse(listViewSubject.Items[i].Text) + ", " + this.reg_id + ")";
dal.InsertUpdateDelete(query);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Hope this.reg_id is also int. If not convert it as I converted the subject id. Please note that I have removed single quote from
'" + listViewSubject.Items[i] + "', '" + this.reg_id + "'
This is the method using parameterized query:
for (int i = 0; i < listViewSubject.Items.Count; i+=2)
{
string query = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES (#subjectID,#StdRegId)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#subjectID",Int.Parse(listViewSubject.Items[i].Text));
command.Parameters.AddWithValue("#StdRegId", this.reg_id);
command.ExecuteNonQuery();
}
It seems like listViewSubject.Items[i] returns a value 'ListViewItem:{2}' rather than an integer. Depending on what kind of object your item collection returns you may want to debug it. Probably listViewSubject.Items[i].Value might work.
I am not sure exactly what your data access layer does behind the scenes, but using the basic SqlCommand I would be inclined to do your insert as follows:
string sql = "INSERT INTO Std_Subjects (subject_id, std_reg_id) VALUES (#SubjectID, #RegID)";
for (int i = 0; i < listViewSubject.Items.Count; i+=2)
{
using (var conn = new SqlConnection(ConnectionString))
using (var command = new SqlCommand(sql, connection))
{
conn.Open();
command.Parameters.Add("#RegID", SqlDbType.Int).Value = this.reg_id;
command.Parameters.Add(SubjectID, SqlDbType.Int).Value = listViewSubject[i].Text;
command.ExecuteNonQuery();
}
}