My Insert Statement Isn't working for Excel in C# - c#

Hey My Insert Statement isn't Working I used the same code for inserting other panel data to excel sheet it's working perfectly there but when I'm trying to insert data in other sheet using second panel it's throwing exception "Insert INTO Statement is not valid" I check every single thing in this i can't find any mistake in it. I'm using OleDb For Insertion.
Here is the same code I've been using for first panel insertion.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
String filename1 = #"E:DB\TestDB.xlsx";
String connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename1 + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
OleDbConnection con = new OleDbConnection(connection);
con.Open();
int id = 4;
string user = txtMUserName.Text.ToString();
string pass = txtMPassword.Text.ToString();
string role = txtMRole.Text.ToString();
DateTime date = DateTime.Now;
string Date = date.ToString("dd/MM/yyyy");
//string Time = date.ToLongTimeString();
string Time = "3:00 AM";
String Command = "Insert into [Test$] (UserID, UserName, Password, Role, Created_Date,Created_Time) VALUES ('"
+ id.ToString() + "','"
+ user + "','"
+ pass + "','"
+ role + "','"
+ Date + "','"
+ Time + "')";
OleDbCommand cmd = new OleDbCommand(Command, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Seems like you are using a reserved name for column Password. you need to escape it with []:
string Command = "Insert into [Test$] (UserID, UserName, [Password], Role, Created_Date,Created_Time) VALUES ('"
+ id.ToString() + "','"
+ user + "','"
+ pass + "','"
+ role + "','"
+ Date + "','"
+ Time + "')";

Related

More columns in the INSERT statement than values in the VALUES clause

I also don't know how to add the values of comboboxes and gender radio buttons to the database. This is basically for a registration form to insert its values into a database. I also need to display the values of the database on the form from selecting the combobox value.
private void Btn_register_Click(object sender, EventArgs e)
{
//int regNo = Cbox_regNo.Text; //i need to get the values from the combobox
string fName = Tbox_fName.Text;
string lName = Tbox_lName.Text;
string dob = dtp_dob.Text;
string address = Tbox_address.Text;
string email = Tbox_email.Text;
string mPhone = Tbox_mPhone.Text;
string hPhone = Tbox_hPhone.Text;
string pName = Tbox_parentName.Text;
string nic = Tbox_nic.Text;
string cNumber = Tbox_cntctNumber.Text;
string connString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\abhin\\Desktop\\Final Project\\Visual Studio\\Final Project\\Final Project\\Student.mdf\";Integrated Security=True";
string Query = "insert into Registrations (regNo, firstName, lastName, dateOfBirth, gender, address, email, mobilePhone, homePhone, parentName, nic, contactNo) values('"+this.Cbox_regNo.Text+"','" + this.Tbox_fName.Text + "','" + this.Tbox_lName.Text + "','" + this.dtp_dob.Value + "','" + this.Tbox_address.Text + "','" + this.Tbox_email.Text + "','" + this.Tbox_mPhone.Text + "','" + this.Tbox_hPhone.Text + "','" + this.Tbox_parentName.Text + "','" + this.Tbox_nic.Text + "','" + this.Tbox_cntctNumber.Text + "') ;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmdDB = new SqlCommand(Query, conn);
SqlDataReader myReader;
try
{
conn.Open();
myReader=cmdDB.ExecuteReader();
MessageBox.Show("Record Added Succesfully", "Register Student", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
while (myReader.Read())
{
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
On declaring your “Query” variable you are using 12 column (regNo, firstName…) and 11 value. You need one more value

I want the corresponding ID of last record in MS Access to appear inside a Message Box [duplicate]

This question already has answers here:
how to get the last record number after inserting record to database in access
(6 answers)
Closed 1 year ago.
Am working with Access as Database in C# (Visual Studio 15). I want to save form entries (add record) into the Access Database and would want the corresponding ID of the record to show in MsgBox upon a successful saving. I have tried the following:
private void Form21_Load(object sender, EventArgs e)
{
try
{
connection.Open();
checkConnection.Text = "Server Connection, Successful";
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error, Server not connected " + ex);
}
}
private void Button6_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into Students_File ([YourNames],[Nationality],[StateOfOrigin],[PlaceOfBirth],[DoB],[HomeAddress],[LastSchools1],[LastClass1],[LastSchools2],[LastClass2],[LastSchools3],[LastClass3],[AdmClass],[CurrentClass],[Guidian],[GuardianContact],[UserName],[PassWord],[Gender],[RegistrationDate]) values('" + YourNames.Text + "','" + Nationality.Text + "','" + StateOfOrigin.Text + "','" + PlaceOfBirth.Text + "','" + DoB.Text + "','" + HomeAddress.Text + "','" + LastSchools1.Text + "','" + LastClass1.Text + "','" + LastSchools2.Text + "','" + LastClass2.Text + "','" + LastSchools3.Text + "','" + LastClass3.Text + "','" + AdmClass.Text + "','" + CurrentClass.Text + "','" + Guidian.Text + "','" + GuardianContact.Text + "','" + UserName.Text + "','" + PassWord.Text + "','" + Gender.Text + "','" + RegistrationDate.Text + "')";
command.ExecuteNonQuery();
//MessageBox.Show("Congrats! Your registration, is successful. You may now click close button, then proceed to login");
command.CommandText = "Select * from Students_File where UserName='" + UserName.Text + "' and PassWord='" + PassWord.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Congrats! Your registration, is successful. You may now click close button, then proceed to login");
this.Close();
}
else if (count > 1)
{
MessageBox.Show("Sorry, the chosen username or password is currently existing or picked by another user. Consequently, your registration was not successful. Do please, decide another but a unique one. Thank you");
}
connection.Close();
}
You can do it this way:
using (OleDbCommand Command = new OleDbCommand("", conn))
{
Command.CommandText = "Your big ugly mess - need to change this to parmaters!)";
Command.Connection.Open();
Command.ExecuteNonQuery();
Command.CommandText = "Select ##Identity";
var intLastID = Command.ExecuteScalar;
MsgBox("Last id into database = " + intLastID);
}
As noted, you do want to change that insert command - it too long, too difficult to maintain, and subject to mistakes in code and even sql injection.
But, for now, you can use the above approach to get/pick up the last ID insert.
In solution to my inquiry, i have the following code (From Kevin):
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("#CategoryName", OleDbType.Integer);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
Now, my challenge is how do i get the ID to appear in messagebox after a successful record creation. Please consider my earliest code in this post in connection with this.

using windows form c# to add values to Mysql database

I need to get the userid(primary key auto_increment) from another table(login) into userdetails table. When trying to run it I keep getting this error " incorrect integer value: 'LAST_INSERT_ID()' for column 'userid' at row 1".
I've tried to take LAST_INSERT_ID() out and run another query after query4 to insert the value into the userid but I can't get it to insert into the right row it just opens a new row.
this is the code am trying to run.
try
{
//This is my connection string i have assigned the database file address path
string MyConnection2 = "datasource=localhost;port=3310;database=e-votingsystem;username=root;password=Password12;";
//this is my insert query in which i am taking input from the user through windows forms
string Query2 = "INSERT INTO vote (username) VALUE ('" + usernameInputBox.Text + "');";
string Query3 = "INSERT INTO login (username,upassword) VALUE ('" + usernameInputBox.Text + "','" + passwordInputBox.Text + "');";
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUES ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text+"');";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query2, MyConn2);
MySqlCommand MyCommand3 = new MySqlCommand(Query3, MyConn2);
MySqlCommand MyCommand4 = new MySqlCommand(Query4, MyConn2);
MySqlDataReader MyReader2;
MySqlDataReader MyReader3;
MySqlDataReader MyReader4;
// opens new connection to database then executes command
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader(); // Here the query will be executed and data saved into the database.
while (MyReader2.Read())
{
}
MyConn2.Close();
// opens new connection to database then executes command
MyConn2.Open();
MyReader3 = MyCommand3.ExecuteReader();
while (MyReader3.Read())
{
}
MyConn2.Close();
//opens new connection to database the exexcutes command
MyConn2.Open();
MyReader4 = MyCommand4.ExecuteReader();
while (MyReader4.Read())
{
}
MyConn2.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
MessageBox.Show("Hello " + forename + surname, "read and accept the terms and conditions to continue");
//new termsAndConditionsPage().Show();
//Hide();
}
As explained in other answer, you have the LAST_INSERT_ID between single quotes and this transform it in a literal string not in a statement to execute. However also removing the quotes I am not sure that you can retrieve the LAST_INSERT_ID using a connection different from the one that originates the AUTOINCREMENT number on the login table. In any case you should use a different approach and, as a first thing, you should remove ASAP the string concatenations and use parameters (Reason: Sql Injection or SurName = O'Neill)
string Query2 = "INSERT INTO vote (username) VALUE (#uname)";
string Query3 = #"INSERT INTO login (username,upassword) VALUE (#uname, #upass);
SELECT LAST_INSERT_ID();";
string Query4 = #"INSERT INTO userdetails
(nationalinsurance,userid,forename,middlename,
surname,housenumber,street,towncity,postcode,suffix)
VALUES (#insurance, #userid, #forename, #middlename,
#surname, #housenum, #street, #town, #postcode, #suffix)";
Now open just one connection and build three commands, all between an using statement
using(MySqlConnection con = new MySqlConnection(.....constring here....))
using(MySqlCommand cmd2 = new MySqlCommand(Query2, con))
using(MySqlCommand cmd3 = new MySqlCommand(Query3, con))
using(MySqlCommand cmd4 = new MySqlCommand(Query4, con))
{
con.Open();
// Add the parameter to the first command
cmd2.Parameters.Add("#uname", MySqlDbType.VarChar).Value = usernameInputBox.Text;
// run the first command
cmd2.ExecuteNonQuery();
// Add parameters to the second command
cmd3.Parameters.Add("#uname", MySqlDbType.VarChar).Value = usernameInputBox.Text;
cmd3.Parameters.Add("#upass", MySqlDbType.VarChar).Value = passwordInputBox.Text;
// Run the second command, but this one
// contains two statement, the first inserts, the
// second returns the LAST_INSERT_ID on that table, we need to
// catch that single return
int userID = (int)cmd3.ExecuteScalar();
// Run the third command
// but first prepare the parameters
cmd4.Parameters.Add("#insurance", MySqlDbType.VarChar).Value = nationalInsuranceInputBox.Text;
cmd4.Parameters.Add("#userid", MySqlDbType.Int32).Value = userID;
.... and so on for all other parameters
.... using the appropriate MySqlDbType for the column type
cmd4.ExecuteNonQuery();
}
you current query has an error
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');SELECT LAST_INSERT_ID();"
try the attached query
In your text query string you have: "','"+"LAST_INSERT_ID()"+"','". Note that the "','"s before and after the "LAST_INSERT_ID()" are incorrectly enclosing the LAST_INSERT_ID() term in single quotes.
Try the following query:
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "',"+"LAST_INSERT_ID()"+",'" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');";

Insert date into an SQL database

So I have another problem doing my school project.
FYI, we don't use sql-parameters and didn't learn how to use them as of yet.
I am trying to insert a birthday into the sql database but I tried everything but there is always a data type mismatch.
Can you guys help me out (without changing the structure of the code)?
You can look it up by searching "birthday" as everything else has German names.
I would really appreciate your help as I'm really desperate.
EDIT: There is a textbox, where user are supposed to type in the birthday. That's where I get the data.
EDIT: I removed all other unnecessary strings etc.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
public class webUser
{
private DateTime _birthday;
public webUser()
{
//
// TODO: Add constructor logic here
//
public DateTime birthday
{
get { return _birhday; }
set { _birthday= value; }
}
public bool checkUser(string eMail)
{
string sql = "SELECT eMail, kennwort FROM Benutzerdatenbank WHERE eMail ='" + eMail + "'";
string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Benutzerdatenbank.accdb");
OleDbConnection con = new OleDbConnection(conStr);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count == 1)
return true;
else
return false;
}
public bool addUser(string eMail, string kennwort, string vorname, string zuname, string telefonnummer, string strasse, string plz, string ort, string firma, string titel, DateTime birthday)
{
if (this.checkUser(eMail) == true)
{
return false;
}
else
{
string zeichen = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghjiklmnopqrstuvwxyz0123456789";
string aktivierungscode = "";
Random rnd = new Random();
for (int i = 1; i < 62; i++)
{
aktivierungscode = aktivierungscode + zeichen.Substring(rnd.Next(0, zeichen.Length - 1), 1);
}
string sql = "INSERT INTO Benutzerdatenbank (eMail, kennwort, Titel, Vorname, Zuname, Firma, birthday, Telefonnummer, Strasse, PLZ, Ort, aktivierungscode) VALUES ('" +
eMail + "','" + kennwort + "','" + titel + "','" + vorname + "','" + zuname + "','" + firma + "','" + birthday+ "','" + telefonnummer + "','" + strasse + "','" + plz + "','" + ort + "','" + aktivierungscode + "');";
string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Benutzerdatenbank.accdb");
OleDbConnection con = new OleDbConnection(conStr);
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return true;
}
}
public void ReadUser(string eMail, string kennwort)
{
string sql = "SELECT * FROM Benutzerdatenbank WHERE eMail='" + eMail + "' AND kennwort ='" + kennwort + "'";
string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Benutzerdatenbank.accdb");
OleDbConnection con = new OleDbConnection(conStr);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count == 1)
{
this.eMail = (string)ds.Tables[0].Rows[0]["eMail"];
this.vorname = (string)ds.Tables[0].Rows[0]["Vorname"];
this.zuname = (string)ds.Tables[0].Rows[0]["Zuname"];
this.telefonnummer = (string)ds.Tables[0].Rows[0]["Telefonnummer"];
this.strasse = (string)ds.Tables[0].Rows[0]["strasse"];
this.plz = (string)ds.Tables[0].Rows[0]["PLZ"];
this.ort = (string)ds.Tables[0].Rows[0]["ORT"];
this.titel = (string)ds.Tables[0].Rows[0]["Titel"];
this.firma = (string)ds.Tables[0].Rows[0]["Firma"];
this.birthday= Convert.ToDateTime(ds.Tables[0].Rows[0]["birthday"];
}
else
{
this.eMail = "";
this.vorname = "";
this.zuname = "";
}
}
}
FYI, we don't use sql-parameters and didn't learn how to use them as of yet.
Then learn how to use them. There is really no point in learning to do it the wrong way. Plus, using dates without parameters is actually more complicated than doing it with parameters.
Parameters are really simple. The following question contains everything you need to get started:
Why do we always prefer using parameters in SQL statements?
The only difference you need to be aware of is that OleDbCommand uses ? instead of #parameterName as the parameter placeholder in the SQL statement. The parameter name is ignored, parameters are added in the order in which the ? placeholders appear.
In your case, the relevant code would look like this:
string sql = "INSERT INTO Benutzerdatenbank (eMail, kennwort, Titel, Vorname, Zuname, Firma, birthday, Telefonnummer, Strasse, PLZ, Ort, aktivierungscode) " +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
OleDbCommand cmd = new OleDbCommand(sql, con);
// The parameter names (first argument) are ignored, the order is important
cmd.Parameters.AddWithValue("#eMail", eMail);
...
cmd.Parameters.AddWithValue("#birthday", birthday);
...
cmd.ExecuteNonQuery();
Format your date parameter as "year date month" with "yyyyMMdd", like: birthday.ToString("yyyyMMdd"). Otherwise, SQL Server tries to convert it from m/d/yyyy format.
string sql = "INSERT INTO Benutzerdatenbank (eMail, kennwort, Titel, Vorname, Zuname, Firma, birthday, Telefonnummer, Strasse, PLZ, Ort, aktivierungscode) VALUES ('" +
eMail + "','" + kennwort + "','" + titel + "','" + vorname + "','" + zuname + "','" + firma + "','" + birthday.ToString("yyyyMMdd") + "','" + telefonnummer + "','" + strasse + "','" + plz + "','" + ort + "','" + aktivierungscode + "');";
It could be that the format of your DateTime object does not match what the SQL database wishes. datetime format to SQL format using C#
This is an example of a insertion in SQL Server with SQL language:
The table is PERSON and this is you struct:
ID, int, primary key, autoincrement
NAME, nvarchar(50), not null
BIRTHDATE, datetime
now, for insert is:
INSERT INTO PERSON (NAME, BIRTHDATE) VALUES('Jose Luis', DATETIMEFROMPARTS(1988, 7, 27, 0,0,0,0));
and for select is:
SELECT * FROM PERSON WHERE BIRTHDATE = DATETIMEFROMPARTS(1988, 7, 27, 0,0,0,0);
this code is testing in SQL Server.
The idea is that you change the value of the variable 'sql' of you code, for example push:
var bithdateformat = string.Format("DATETIMEFROMPARTS({0}, {1}, {2}, {3}, {4}, {5}, {6})", birthday.Year, birthday.Month, birthday.Day, 0, 0, 0, 0);
string sql = "INSERT INTO Benutzerdatenbank (eMail, kennwort, Titel, Vorname, Zuname, Firma, birthday, Telefonnummer, Strasse, PLZ, Ort, aktivierungscode) VALUES ('" +
eMail + "','" + kennwort + "','" + titel + "','" + vorname + "','" + zuname + "','" + firma + "','" + bithdateformat + "','" + telefonnummer + "','" + strasse + "','" + plz + "','" + ort + "','" + aktivierungscode + "');";

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();
}
}

Categories