I have an error with my code.
Code execution directly flows to the catch block and says: incorrect syntax near ');
I want to save a file in the database and call it again.
public partial class newsrv : System.Web.UI.Page{
string dir = "C://fileup//";
protected void Page_Load(object sender, EventArgs e){
if (!Directory.Exists(dir)){
Directory.CreateDirectory(dir);
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){
}
protected void Button1_Click(object sender, EventArgs e){
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|DB.mdf;Integrated Security=True;User Instance=True");
string fname = FileUpload1.PostedFile.FileName;
try{
SqlCommand cmd = new SqlCommand("INSERT INTO OrderNum (SrviceType, Msg,[File]) VALUES ('" + DropDownList1.SelectedItem.Text + "','" + TextBox1.Text + "' ,'" + FileUpload1.PostedFile.FileName + "') );", con);
con.Open();
try {
int res = cmd.ExecuteNonQuery();
if (res > 0){
System.Windows.Forms.MessageBox.Show("success");
}
Label2.Text = TextBox1.Text;
FileUpload1.SaveAs(dir + fname);
Label1.Text = " file name uploaded succ ";
FileUpload1.Visible = true;
}catch (Exception ex){
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}catch{
Label1.Text = " file name not uploaded ";
FileUpload1.Visible = false;
con.Close();
}finally{
con.Close();
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e){
}
}
It looks like you have an extra ); at the end of the SQL statement...
... + TextBox1.Text + "' ,'" + FileUpload1.PostedFile.FileName + "') );", con);
^^
remove these
I think you should get rid of ); in:
"') );",
Also, consider using placeholders for better security.
Your SQLCommand is invalid. It should be:
SqlCommand cmd = new SqlCommand("INSERT INTO OrderNum (SrviceType, Msg,[File]) VALUES ('" + DropDownList1.SelectedItem.Text + "','" + TextBox1.Text + "' ,'" + FileUpload1.PostedFile.FileName + "')", con);
E.G. Remove the extra ); at the end of the statement.
Don't put ); at the end of the query. And for an easy compresion use this syntax:
SqlCommand cmd=new SqlCommand(String.Format(#"INSERT INTO OrderNum (SrviceType, Msg,[File]) VALUES ('{0},{1},{2}')",DropDownList1.SelectedItem.Text, TextBox1.Text,FileUpload1.PostedFile.FileName),con);
For better understanding change the name of the obj in something that remember what you want do with this.
Example if you have a textbox that required the username call the textbox txtUserName or txtNickName
Related
This is my C# code and my issue as the title says is my checkbox values are not going into my access database, or at least not changing them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
Label1.Text = (string)Session["sesionicontrol"];
}
protected void txtPass_TextChanged(object sender, EventArgs e)
{
}
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//Declare Variables
string username = txtEmailLogin.Text;
string password = txtPasswordLogin.Text;
username = username.Trim().ToLower();
password = password.Trim().ToLower();
//Handle null or empty fields
if ((string.IsNullOrEmpty(username)) || (string.IsNullOrEmpty(password)))
{
lblError.Text = "Please Enter a vaild Username or Password";
}
else if (((username.Contains("#mu.edu") || (username.Contains("#marquette.edu")))))
{
//Run select query and populate a table, then check to see if the user and pass are in that table
OleDbConnection conn = null;
DataTable dt = new DataTable();
try
{
string connString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "Select Count(*) From Team Member Where Email = ? AND Pass = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
// handle error here
}
finally
{
conn.Close();
}
//checking if there is a result in the virtual table, if there is they successfully logged in
if (dt.Rows.Count >= 0)
{
lblError.Text = "Welcome!";
/// Take to Homepage
CommonClass.txtEmail = txtEmailLogin.Text;
Server.Transfer("HomePage.aspx", true);
}
else
{
lblError.Text = "Incorrect Username or Password";
}
}
}
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
DataTable gridTable = new DataTable();
try
{
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "INSERT INTO [Team Member] (FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major) VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" + txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "')";
string query1 = "INSERT INTO [Team Member] (Soccer, Basketball, Football, Softball) VALUES('" + c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
lblError1.Text = ("Registered Successfully");
}
catch (Exception ex)
{
lblError1.Text = ("Error occurred: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void btnReg_Click(object sender, EventArgs e)
{
txtFirst.Visible = !txtFirst.Visible;
txtLast.Visible = !txtLast.Visible;
txtEmail.Visible = !txtEmail.Visible;
txtPass.Visible = !txtPass.Visible;
txtPassConfirm.Visible = !txtPassConfirm.Visible;
btnRegister.Visible = !btnRegister.Visible;
btnReg.Visible = !btnReg.Visible;
c1.Visible = !c1.Visible;
c2.Visible = !c2.Visible;
c3.Visible = !c3.Visible;
c4.Visible = !c4.Visible;
txtAge.Visible = !txtAge.Visible;
txtHobbies.Visible = !txtHobbies.Visible;
txtFavorite.Visible = !txtFavorite.Visible;
txtMajor.Visible = !txtMajor.Visible;
lbl1.Text = "Sports you want to play";
lbl2.Text = "Age";
lbl3.Text = "Hobbies";
lbl4.Text = "Favorite Color";
lbl5.Text = "Major";
}
protected void c2_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void c1_CheckedChanged(object sender, EventArgs e)
{
}
}
My database looks like this
If you are appending to Access Yes/No fields then I would try removing the single quotes (') from the second INSERT INTO line:
string query1 = "INSERT INTO [Team Member]
(Soccer, Basketball, Football, Softball)
VALUES(" + c1.Checked.ToString() + ", "
+ c2.Checked.ToString() + ", "
+ c3.Checked.ToString() + ", "
+ c4.Checked.ToString() + ")";
First, The reason your check box values never get inserted is because your OleDbCommand is defined like this:
OleDbCommand cmd = new OleDbCommand(query, conn);
Using query as the command.text. query1 is never referenced to this and thus never executes.
Second (more important), you need to have the insert statement as one statement, not 2. Calling 2 Insert statements would cause 2 rows to added to the table. One containing values from query, and one containing the checkbox value from query1. You should define your query in one string like this
string query = "INSERT INTO [Team Member] " +
"(FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major, Soccer, Basketball, Football, Softball) " +
"VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" +
txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "','" +
c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
I have a file upload function that throws sql exception
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ','.
The identifier that starts with
'PGFzcDpHcmlkVmlldyBJRD0iR3JpZFZpZXcyIiANCiAgICAgICAgcnVuYXQ9InNlcnZlciI
gV2lkdGg9IjgyMHB4IiBBdXRvR2VuZXJhdGVTZWxlY3RCdXR0b249IlRy' is too long.
Maximum length is 128" whenever the file name contains a single quote character (')
File upload function below :
protected void btn_file_upload_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.HasFile)
{
byte[] byte_file = FileUpload1.FileBytes;
string str_file = Convert.ToBase64String(byte_file);
SqlCommand cmd = new SqlCommand("insert into spt_files values('" + FileUpload1.FileName + "','" + str_file + "','" + dd_students.Text + "')", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
lbl_file_upload.Text = "File uploaded!";
}
else
lbl_file_upload.Text = "Choose a file";
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
How to resolve this?
You can use
protected void btn_file_upload_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.HasFile)
{
byte[] byte_file = FileUpload1.FileBytes;
string str_file = Convert.ToBase64String(byte_file);
SqlCommand cmd = new SqlCommand("insert into spt_files values('" + FileUpload1.FileName.Replace("'", "''") + "','" + str_file + "','" + dd_students.Text + "')", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
lbl_file_upload.Text = "File uploaded!";
}
else
lbl_file_upload.Text = "Choose a file";
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
And increase the size of column in table .
I trying to update my profile but it keep catching the old data when it update. What can be done to solve this problem. Please help me out on this problem thanks!
protected void Page_Load(object sender, EventArgs e)
{
String nric = (String)Session["nric"];
SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI");
con.Open();
SqlCommand cm = new SqlCommand("Select * from MemberAccount where nric = '" + nric + "'", con);
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
txtFullName.Text = dr["fullname"].ToString();
txtAddress.Text = dr["address"].ToString();
txtContact.Text = dr["contact"].ToString();
txtEmail.Text = dr["email"].ToString();
}
con.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
String nric = (String)Session["nric"];
if (txtContact.Text.Equals("") || txtEmail.Text.Equals(""))
{
lblMessage.Text = "Do not leave blank fill to update your profile!";
}
else
{
string strQuery = "Update MemberAccount Set address = '" + txtAddress.Text + "', contact = '" + txtContact.Text + "', email = '" + txtEmail.Text + "' Where nric = '" + nric + "'";
SqlCommand cmd = new SqlCommand(strQuery);
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Profile Updated.";
}
}
Sounds like you could just apply an IsPostBack check in your Page_Load method. http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
// Load data
}
}
Note: your code looks susceptible to SQL injection.
I have tried so many types I don't know how to insert.
Is there any problem with sql server?
PLEASE HELP ME FAST..
SqlConnection con = new SqlConnection( "Data Source=localhost/SQLEXPRESS.Polaris.dbo;Initial Catalog=Polaris;Integrated Security=True;Pooling=False");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button3_Click(object sender, EventArgs e)
{
con.Open();
SqlDataReader rdr = null;
//string s1 = "insert into Login values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Value + "'";
SqlCommand cmd1 = new SqlCommand("insert into Login values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Value + "'");
cmd1.Connection = con;
rdr = cmd1.ExecuteReader();
Label2.Visible = true;
//EndEventHandler.RemoveAll();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
Cannot implicitly convert type 'WebApplication4.SqlConnection' to
'System.Data.SqlClient.SqlConnection'
According to error you have class called SqlConnection in WebApplication4 namespace. You may have mistakenly generate that class. you need to remove that class first and then add reference to System.Data.SqlClient
Here's what you can do:
SqlConnection con = new SqlConnection( "Data Source=localhost/SQLEXPRESS.Polaris.dbo;Initial Catalog=Polaris;Integrated Security=True;Pooling=False");
protected void Button3_Click(object sender, EventArgs e)
{
con.Open();
string s1 = "insert into Login values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Value + "'";
SqlCommand cmd = new SqlCommand(s1, con);
cmd.ExecuteNonQuery();
}
i am beginner with sql,
I have comments Template with button in the end of it to add the new comment to the database ,so i use SQL INSERT code to add and it works fine. but after button postback , the the new comment does not shows in my label until i refresh the page manually! .
this my code in c# code portion:
protected void Page_Load(object sender, EventArgs e)
{
ViewComments();
}
private void ViewComments()
{
hookUp =
new SqlConnection("Server=xxxx\\SQLEXPRESS;Database=WebExcerciseDB;" + "Integrated Security=True");
SqlCmd = new SqlCommand("SELECT PersonName,PersonMail,Comment FROM CommentsTable", hookUp);
try
{
hookUp.Open();
reader = SqlCmd.ExecuteReader();
while (reader.Read())
{
SQL_Result.Text += reader["PersonName"] + " " + reader["PersonMail"] + " " + reader["Comment"] +
"<br/>";
}
}
catch (Exception)
{
MessageBox.Show("Error in database code\n");
}
finally
{
reader.Close();
hookUp.Close();
}
}
protected void AddCommentBtn_Click(object sender, EventArgs e)
{
// SQL First INSRET Way //
//string InsertSQLString = "INSERT INTO CommentsTable(PersonName,PersonMail,Comment,PostDate) VALUES ('" +
// PersonName.Text + "','"+ PersonMail.Text + "','" + PersonComment.Value + "','" +
// DateTime.Now + "')";
//hookUp =
// new SqlConnection("Server=xxxx-PC\\SQLEXPRESS;Database=WebExcerciseDB;" + "Integrated Security=True");
//SqlCmd = new SqlCommand(InsertSQLString, hookUp);
//hookUp.Open();
//SqlCmd.ExecuteNonQuery();
//hookUp.Close();
// SQL First INSRET Way End //
// SQL second INSRET Way //
string InsertSQLString = "INSERT INTO CommentsTable(PersonName,PersonMail,Comment,PostDate)VALUES(#Name,#Mail,#Comment,#Date)";
hookUp =
new SqlConnection("Server=xxxx-PC\\SQLEXPRESS;Database=WebExcerciseDB;" + "Integrated Security=True");
SqlCmd = new SqlCommand(InsertSQLString, hookUp);
SqlCmd.Parameters.Add("#Name", PersonName.Text);
SqlCmd.Parameters.Add("#Mail", PersonMail.Text);
SqlCmd.Parameters.Add("#Comment", PersonComment.Value);
SqlCmd.Parameters.Add("#Date", DateTime.Now);
hookUp.Open();
SqlCmd.ExecuteNonQuery();
hookUp.Close();
// SQL second INSRET Way End //
}
}
}
thanks any way..
the reader is not the problem. The problem is order in which your methods are called.
this should help: http://msdn.microsoft.com/en-us/library/ms178472.aspx#lifecycle_events