I have a create account page and on the page I have one button to insert all the details into two seperate tables one of the tables Pictures is dependant on the User table 1:1 relationship via UserID.
I have written some code to try get the last insert id so I can insert into the pictures table:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme, username, password) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "')", cn);
OdbcCommand sc = new OdbcCommand("SELECT LAST_INSERT_ID()", cn);
//convert LAST INSERT into string theUserId
string filenameDB = Path.GetFileName(FileUpload1.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
Label10.Text = "Upload status: File uploaded!";
OdbcCommand cm = new OdbcCommand("INSERT INTO Pictures (picturepath, UserId) VALUES ('" + fileuploadpaths + "', " + theUserId + ")", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Label10.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
//e.Authenticated = true;
//Response.Redirect("Login.aspx");
// Event useradded is true forward to login
}
}
}
Not sure if this is correct and I also need to know how to convert the select statement into a string so I can retrieve the UserID from the User table, see database structure:
EDIT
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme, username, password) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "')SELECT LAST_INSERT_ID()", cn);
//OdbcCommand sc = new OdbcCommand("SELECT LAST_INSERT_ID()", cn);
//convert LAST INSERT into string theUserId
//using (DataTable dt = DataTier.ExecuteQuery(cmd))
////error for datatable and datatier
//if (dt.Rows.Count == 1)
//{
// //Read the new ID from the record that has just been inserted
// string theUserId = dt.Rows[0]["UserID"].ToString();
using (OdbcDataReader reader = cmd.ExecuteReader())
{
string theUserId = String.Format("{0}", reader.GetString(0));
string filenameDB = Path.GetFileName(FileUpload1.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
Label10.Text = "Upload status: File uploaded!";
OdbcCommand cm = new OdbcCommand("INSERT INTO Pictures (picturepath, UserId) VALUES ('" + fileuploadpaths + "', " + theUserId + ")", cn);
cn.Open();
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Label10.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
//e.Authenticated = true;
//Response.Redirect("Login.aspx");
// Event useradded is true forward to login
}
}
}
You can use a query similar to the following to post a record, then get the ID.
string sQuery = #"INSERT INTO [ExpenseType]
(
[ExpenseTypeName]
,[Deleted]
,[IsTaxable]
,[UpdatedDate]
,[UpdatedUser]
,[ParentCategoryComponentID]
,[CategoryComponentID]
,[NLNominalAccountID]
,[SYSTaxCodeID]
)
VALUES
(
#ExpenseTypeName
,#Deleted
,#IsTaxable
,#UpdatedDate
,#UpdatedUser
,#ParentCategoryComponentID
,#CategoryComponentID
,#NLNominalAccountID
,#SYSTaxCodeID
)
SELECT SCOPE_IDENTITY() AS 'ID' ";
using ( SqlCommand oSqlCommand = new SqlCommand( sQuery ) )
{
oSqlCommand.Parameters.AddWithValue( "#ExpenseTypeName", this.ExpenseTypeName );
oSqlCommand.Parameters.AddWithValue( "#Deleted", this.Deleted );
oSqlCommand.Parameters.AddWithValue( "#IsTaxable", this.IsTaxable );
oSqlCommand.Parameters.AddWithValue( "#UpdatedDate", base.GetUpdatedDate() );
oSqlCommand.Parameters.AddWithValue( "#UpdatedUser", base.GetUpdatedUser() );
oSqlCommand.Parameters.AddWithValue( "#ParentCategoryComponentID", this.ParentCategoryComponentID );
oSqlCommand.Parameters.AddWithValue( "#CategoryComponentID", this.CategoryComponentID );
oSqlCommand.Parameters.AddWithValue( "#NLNominalAccountID", this.NLNominalAccountID );
oSqlCommand.Parameters.AddWithValue( "#SYSTaxCodeID", this.SYSTaxCodeID );
using ( DataTable dt = DataTier.ExecuteQuery( oSqlCommand ) )
{
if ( dt.Rows.Count == 1 )
{
//Read the new ID from the record that has just been inserted
string RecordID = dt.Rows[ 0 ][ "ID" ].ToString();
}
}
}
Note the SELECT SCOPE_IDENTITY() AS 'ID' at the end of the query.
and
if ( dt.Rows.Count == 1 )
{
//Read the new ID from the record that has just been inserted
string RecordID = dt.Rows[ 0 ][ "ID" ].ToString();
}
Related
I'm getting syntax error in all my inputs into the textboxes.
In my database all the requirement is string other than the ID which is an autonumber, I try to search for possible answer but all didn't work or maybe I just missed some answer
Here is the error:
Syntax error (missing operator) in query expression ''hasdasd'password
= 'h'account_Type='Manager'Name='h'Middle_Name='h'Surname'h'address'h'BirthDate='3/17/1999'Mobile_Number'65465''.
Code:
private void update_Click(object sender, EventArgs e)
{
DateTime bdate = DateTime.Parse(birthdate.Value.ToShortDateString());
DateTime currentDate = DateTime.Parse(DateTime.Now.Date.ToShortDateString());
int age = currentDate.Year - bdate.Year;
String id = emp_view.SelectedRows[0].Cells[0].Value + String.Empty;
int id1 = Int32.Parse(id);
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\dbms\jollibee.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "update Employee_Details set username = '" + username.Text +
"'password = '" + password.Text +
"'account_Type='" + accountType.Text +
"'Name='" + name.Text +
"'Middle_Name='" + middlename.Text +
"'Surname'" + surname.Text +
"'address'" + address.Text +
"'BirthDate='" + birthdate.Value.ToShortDateString() +
"'Mobile_Number'" + mobilenumber.Text +
"'where ID = '" + id1 + "'";
if (username.Text.Equals("") ||
username.Text.Equals("") ||
password.Text.Equals("") ||
middlename.Text.Equals("") ||
surname.Text.Equals("") ||
address.Text.Equals("") ||
accountType.Text.Equals("") ||
mobilenumber.Text.Equals("")
)
{
MessageBox.Show("Please fill all fields.");
con.Close();
}
else if (age < 18)
{
MessageBox.Show("You are not allowed to work because you are under age..");
con.Close();
}
else
{
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(username.Text + "is now updated on database.");
list();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In your existing code, there are issues like.
1- Column in update are not separated by ","
2- All string are not separated using quotes ''
You should always avoid writing queries inline by concatenation of string. This will make you code vulnerable to SQL Injection.
To read more about SQL Injections check here
Change your code like following using command parameters.
cmd.CommandText = "update Employee_Details set [username] = #un, [password] = #pw, [account_Type]= #at, [Name] = #nm, [Middle_Name]= #mn, [Surname]= #sn, [address]= #add, [BirthDate] = #bd, [Mobile_Number] = #mn WHERE [Id]=#id";
cmd.Parameters.Add("#un", OleDbType.VarChar).Value = username.Text;
cmd.Parameters.Add("#pw", OleDbType.VarChar).Value = password.Text;
cmd.Parameters.Add("#at", OleDbType.VarChar).Value = accountType.Text;
cmd.Parameters.Add("#nm", OleDbType.VarChar).Value = name.Text;
cmd.Parameters.Add("#mn", OleDbType.VarChar).Value = middlename.Text;
cmd.Parameters.Add("#sn", OleDbType.VarChar).Value = surname.Text;
cmd.Parameters.Add("#add", OleDbType.VarChar).Value = address.Text;
cmd.Parameters.Add("#bd", OleDbType.Date).Value = Convert.ToDateTime(birthdate.Value);
cmd.Parameters.Add("#mn", OleDbType.VarChar).Value = mobilenumber.Text;
cmd.Parameters.Add("#id", OleDbType.VarChar).Value = id1;
Note: You need to correct the datatype based on your table structure as it is now known to me.
Your completely malformed SQL should look like:
cmd.CommandText = "update Employee_Details set " +
"username = '" + username.Text + "',"+
"[password] = '" + password.Text + "'," +
"account_Type = '" + accountType.Text + "'," +
"[Name] = '" + name.Text + "'," +
"Middle_Name = '" + middlename.Text + "'," +
"Surname = '" + surname.Text + "'," +
"address = '" + address.Text + "'," +
"BirthDate = #" + birthdate.Value.ToString("yyyy'/'MM'/dd") + "#," +
"Mobile_Number = '" + mobilenumber.Text + "' " +
"where ID = " + id1 + "";
That said, DO use parameters as already explained. Much easier and safer.
I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:
And here is my code:
public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
{
if (beoordelingBest < beoordeling)
{
titelBest = titel;
beoordelingBest = beoordeling;
}
string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
command = new SqlCommand(queryString, con);
Can someone please help me with this? I can't figure it out.
Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
If you have multiple queries each unique parameter value should have its own parameter name/value
Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
Never reuse connections as global objects, create, use, and destroy them when needed.
Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.
var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT #a1Voornaam, #a1Achternaam, FilmID from Films WHERE titel = #title";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
command.Parameters.Add(new SqlParameter("#a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
command.Parameters.Add(new SqlParameter("#achternaam", SqlDbType.VarChar){Value = achternaam});
command.Parameters.Add(new SqlParameter("#title", SqlDbType.VarChar){Value = title});
con.Open();
command.ExecuteNonQuery();
}
Perhaps one of your values is ');
That would terminate the INSERT statement early, and cause the error.
|
V
INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');
You should use SqlParameters instead of string concatenation.
Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
try
{
string query = "insert into UserDetail(Name,Address)
values('" + txtName.Text + "','" + txtAddress.Text + "');";
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.SelectCommand.ExecuteNonQuery();
con.Close();
lblmessage.Text = "Data saved successfully.";
}
catch
{
con.Close();
lblmessage.Text = "Error while saving data.";
}
}
i want to create one label, Label name empty.
now i change label name using this code :
MainMenu frm = new MainMenu();
try
{
con = new SqlConnection(cs.DBConn);
con.Open();
String sql = "SELECT SSUserID from SSUserInformation where UserName like '" + txtUserName.Text + "%'";
cmd = new SqlCommand(sql, con);
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
frm.lbluserid.Text = rdr[0].ToString();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
then i save label name to database using this code :
insert into UserInfo(UserID) Values(frm.lbluserid.Text);
the problem is recored save but is empty not any value stored into database
what if you change your sql
String sql = "INSERT INTO UserInfo(UserID) " +
"SELECT SSUserID from SSUserInformation where UserName like '" + txtUserName.Text + "%'";
EDIT
string SQL = "INSERT INTO [UserInfo] ([UserID]) VALUES (#UserName) " +
" SELECT [SSUserID] FROM [SSUserInformation] WHERE [UserName] LIKE #UserName + '%' ";
SqlCommand cmd = new SqlCommand(SQL);
cmd.Parameters.AddWithValue("#UserName", txtUserName.Text);
cmd.ExecuteNonQuery();
public static string SaveSales(string aa, string bb, string cc, string dd, string ee, string ff, string gg,string hh,string ii)
{
OleDbConnection myConnection = GetConnection();
string myQuery = "INSERT INTO Sales VALUES ( '" + aa + "' , '" + bb + "','" + cc + "','" + dd + "','" + ee + "' ,'" + ff + "' ,'" + gg + "','" + hh + "','" + ii + "' );";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
I am assigning the value to the variable from the text box on the page during the pageupload event of AjaxFileUpload1.The problem is that, I am not getting the value from the text box to my variable even though no error throws.My variables are
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
Any idea why AjaxFileUpload1_UploadComplete is not able to read text box value
My cs Code is:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
Please help me
I spent some time last week investigating this question but in the end couldn't find an easy solution for this. The OP in that question solved it by storing values in the Session but for this to work you would still need to cause a postback at some stage.
There apparently was functionality planned for the AjaxFileUpload control to pass values in the Context Keys collections but this was never implemented. This question describes how to implement this yourself though.
I think I saw another question around the same topic and the OP solved it by changing to using the AsyncFileUpload control but I stand to be corrected...
i think you need to add !Page.IsPostBack to your code. like this
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
if(!Page.IsPostBack)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
}
protected void save_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
try
{
string connString = "Provider=OraOLEDB.Oracle;Data Source=127.0.0.1;User ID=SYSTEM;Password=SYSTEM;Unicode=True";
conn = new OleDbConnection(connString);
conn.Open();
string strQuery = "update login set fname ='" + TextBox4.Text + "' and lname='" + TextBox5.Text + "' and place='" + TextBox6.Text + "' and dob='" + TextBox7.Text + "' where uname='" + Label1.Text + "'";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
OleDbDataReader obReader = obCmd.ExecuteReader();
}
catch (OleDbException ex)
{
Response.Write("Send failure: " + ex.ToString());
}
catch (Exception exe)
{
Response.Write(exe.Message);
}
finally
{
if (null != conn)
{
conn.Close();
}
}
}
the update query syntax is wrong.
You cannot use AND while setting multiple columns. It should be seperated by comma.
string strQuery = "update login set fname ='" + TextBox4.Text + "',lname='" +
TextBox5.Text + "',place='" + TextBox6.Text + "',dob='" + TextBox7.Text +
"' where uname='" + Label1.Text + "'";
The values must be separated with a comma and there is one big problem in this code. Imagine what happens when someone puts the following into TextBox4:
' where 1 = 1 --
The result would be a table where all entries would be overwritten
update login set fname ='' where 1 = 1 --', lname='bla' ....
Use DbParameter instead:
string strQuery = #"
update LOGIN set
FNAME = :FNAME,
LNAME = :LNAME,
PLACE = :PLACE,
DOB = :DOB
where
UNAME = :UNAME
";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
obCmd.Parameters.AddWithValue(":FNAME", TextBox4.Text);
obCmd.Parameters.AddWithValue(":LNAME", TextBox5.Text);
obCmd.Parameters.AddWithValue(":PLACE", TextBox6.Text);
obCmd.Parameters.AddWithValue(":DOB", TextBox7.Text);
obCmd.Parameters.AddWithValue(":UNAME", Label1.Text);
OleDbDataReader obReader = obCmd.ExecuteReader();
For Oracle the : should indicate a parameter (it's a # for Sybase and MS SQL). I named all params like the target columns, but you can use other names of course.