ExecuteNonQuery: Connection property has not been initialized? - c#

I get an error in my code:
ExecuteNonQuery: Connection property has not been initialized.
This could be due to the line in this code:
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')");
Full code:
{
string theUserId = Session["UserID"].ToString();
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
}
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
//FileUploadControl.SaveAs(Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
FileUploadControl.SaveAs(Path.Combine(fileuploadpath, filename));
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')");
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
There is another problem, I dont think its an insert I want as this is going to make a duplicate entry within my database, would it just be a case of changing it from INSERT INTO to UPDATE?
Also is there a way to overwrite upon uploading the image? Atm it just saving the image into the same folder as the one I already have? The first image or any image obviously isnt going to have the same file name so how would I go about overwriting any image in the folder with the one im uploading?
EDIT:
New error (fileupload works as its stored in the correct area but passing the fileupload to the insert statement is abit wonky)
I get the error
The file could not be uploaded. The following error occured: ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.5.9]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''C:\Users\Garrith\Documents\Visual Studio 2010\WebSites\WebSite1\userdata\1\uplo' at line 1
Which is kind of strange?
All im trying to do is save the filepath+filename in mydb my attempt at passing to the insert has obviously failed.
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
string filename = Path.GetFileName(FileUploadControl.FileName);
//FileUploadControl.SaveAs(Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
FileUploadControl.SaveAs(Path.Combine(fileuploadpath, filename));
StatusLabel.Text = "Upload status: File uploaded!";
//some kind of function to take the path then enter it into my insert syntax?
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
As you can see on this line:
VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
im missing the "filename" i tryed this:
VALUES ('" + theUserId + "' , '" + fileuploadpath, filename + "')", cn);
Cheap shot lol but worth a go I guess and it cryed as it always does!

You need to associate the connection with the cmd:
OdbcCommand cmd =
new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')");
cmd.Connection = cn; // <--------
cmd.ExecuteNonQuery();
Also, remove the braces here:
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};
Server=localhost; Database=gymwebsite2; User=root; Password=commando;"); cn.Open();
}

You want to create the OdbcCommand using CreateCommand on OdbcConnection. The code as posted does not tie cmd to cn. Also, you should use CommandParameters instead of inlining the values (to guard against SQL injection attacks).
OdbcCommand cmd = cn.CreateCommand();
cmd.CommandText = "INSERT INTO Pictures (UserID, picturepath) VALUES (?, ?)";
cmd.Parameters.Add(new OdbcParameter("#UserID", OdbcType.Int, theUserID));
cmd.Parameters.Add(new OdbcParameter("#picturepath", OdbcType.VarChar, fileuploadpath));
cmd.ExecuteNonQuery();

This is the problem:
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')"); <--- there is no connection intialize here
Change it to:
//eg: odbconnection cn = new odbcconnection();
string fileup = fileupload + "," filename;
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileup.ToString() + "')",cn);
Regards

The following is syntactically fubar'd:
string theUserId = Session["UserID"].ToString();
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
}

Related

when i fire insert query i get Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

I am new to this forum and new to C# web programming. I am developing LMS (Library Management system) using SQL Server and Visual Studio ver 16. I have an issue with the insertion of data into the database. the same code I used in other pages and work perfectly. put hardcoded values in insert statement and it worked perfectly which means that there is no issue with connection to database so where is the issue? it can be the text boxes etc name and property which I also checked and found correct. code is as follows
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
// SqlCommand cmd = con.CreateCommand();
//cmd.CommandType = CommandType.Text;// beow is the way to write a query like ist put '' then iside we have "" and then isde we have ++ and then inside we have text box name
// cmd.CommandText= "INSERT INTO member_master_tbl values('"++"','"++"','"++"','"++"','"++"','"++"','"++"','"++"','"++"')"
// cmd.CommandText = "INSERT INTO member_master_tbl (full_name,dob,contact_no,email,state,city,pincode,full_address,member_id,password) values ('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "','"+TextBox4.Text.Trim()+"','" + TextBox3.Text.Trim() + "','" + DropDownList1.SelectedItem.Value + "','" + TextBox6.Text.Trim() + "','" + TextBox7.Text.Trim() + "','" + TextBox5.Text.Trim() + "','" + TextBox8.Text.Trim() + "','" + TextBox9.Text.Trim() + "');";
//notr thr col nsmes in the query are case sensitive
String status = "pending";
SqlCommand cmd = new SqlCommand("INSERT INTO member_master_tbl (full_name,dob,contact_no,email,state,city,pincode,full_address,member_id,password,account_status)values(#full_name,#dob,#contact_no,#email,#state,#city,#pincode,#full_address,#member_id,#password,#account_status);", con);
cmd.Parameters.AddWithValue("#full_name", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#dob", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#contact_no", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("#email", TextBox4.Text.Trim());
cmd.Parameters.AddWithValue("#state", DropDownList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#city", TextBox6.Text.Trim());
cmd.Parameters.AddWithValue("#pincode", TextBox7.Text.Trim());
cmd.Parameters.AddWithValue("#full_address", TextBox5.Text.Trim());
cmd.Parameters.AddWithValue("#member_id", TextBox8.Text.Trim());
cmd.Parameters.AddWithValue("#password", TextBox9.Text.Trim());
cmd.Parameters.AddWithValue("#account_status",status);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('Sign Up Successful. Go to User Login to Login');</script>");
}
catch (SqlException ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}

Error - Insert data into Access database in c#

Pls, am having an error code when inserting data into Access database. It keeps saying there's sytanx error in my INSERT INTO statement. Can any one help me to solve this.
Here is the code
try {
OleDbConnection connection = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\DELL\Documents\EmployeesData.accdb;
Persist Security Info = false;");
connection.Open();
OleDbCommand cmd = new OleDbCommand("insert into EmployeeInfo (UserName, Password) values('" + UserText.Text + "', '" + PassText.Text + "')", connection);
cmd.ExecuteNonQuery();
MessageBox.Show("Inserted");
}
catch (Exception ex)
{
MessageBox.Show("Failed" + ex.ToString());
}
Password is a keyword in MSACCESS so u need to enclosed in [] bracket
OleDbCommand cmd = new OleDbCommand("insert into EmployeeInfo ([UserName], [Password])
values('" + UserText.Text + "', '" + PassText.Text + "')", connection);
Note: always use parameterized queries to avoid SQL Injection

Error SQL INSERT INTO with Odbc Command C#

Scenario:
I want to input data from textbox into the database based on microsoft data base (.mdb)
I already searching and find good clue and my result was here.
This Code below was inside command button click event:
using (OdbcConnection conn= new OdbcConnection())
{
conn.ConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=C:\\BlaBlaBla.mdb;Uid=Admin;Pwd=;";
conn.Open();
using (OdbcCommand cmd = new OdbcCommand(
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
And when I click the command button, I get unfriendly exception
ERROR [42S02] [Microsoft][ODBC Microsoft Access Driver] Could not find
output table 'TABLENAME'.
That happened when I insert cmd.ExecuteNonQuery. If I didn't insert that, of course nothing happens in my table target.
So what mistakes did I make in that code? What should I do?
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", myConnection))
change this into
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", Conn))
you define Conn as your connection string not "myConnection"
So i changed to OleDbConnection And My Problem Cleared,
using (OleDbConnectionconn= new OleDbConnection())
{
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\LOSERONE\Documents\DATABASE\Latihan1.mdb";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand (
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
Seems, to connected the database must same as the connection string in the properties on the targeted database.
Does anyone can tell me what is the difference OleDbConnection with OdbcConnection in .mdb database file?!
This problem is because sql connection's default database after login is not the same where your table 'TABLENAME' exists. Try to add database name before table like this:
INSERT INTO DBNAME..TABLENAME (FIELD1, FIELD2)
replace your myConnection to Conn

Use right syntax error in Mysql

Am not able to fix the error below:
`"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'When,Then) values( '79','WBT-CoE','gyj','yi','yi')' at line 1"` error.
Here's the code:
protected void Button3_Click(object sender, EventArgs e){
string MyconnectionString = "server=localhost;database=requirement_doc;Uid=t;Pwd=123;";
MySqlConnection conn = new MySqlConnection(MyconnectionString);
MySqlCommand cmd;
DataTable dt1 = new DataTable();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT Req_ID, Actor FROM UseCase where Req_ID='" + txtReqID.Text + "' AND Actor='" + DropDownList1.Text + "'";
MySqlDataAdapter da1 = new MySqlDataAdapter();
da1.SelectCommand = cmd;
da1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
Label1.Text = "Data already exist";
}
else
{
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,When,Then) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
}
try
{
cmd.ExecuteNonQuery();
Label1.Text = " Successfully saved";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
Surround When and then with `` because they are reserved names.
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,`When`,`Then`) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
When and Then are reserved names in MySQL. So if you use those as column names, you get that error.

Error trying to add filename to end of string:

Error trying to add filename to end of string:
if (FileUploadControl.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
string filename = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
// error on this line filename only assignment, call can be used as a statement
FileUploadControl.SaveAs(Server.MapPath(fileuploadpath));
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
If I try it this way:
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
FileUploadControl.SaveAs(Path.Combine(fileuploadpath, filename));
I get a mysql error as there is no filename added to the end of the path (btw im only trying to save the path not the image) altho technically i should still be able to insert half a filepath into sql so maybe this error isnt related to my original upload method using the code above. But obviously I still need the full pathname.
The file could not be uploaded. The following error occured: ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.5.9]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''C:\Users\Garrith\Documents\Visual Studio 2010\WebSites\WebSite1\userdata\1\uplo' at line 1
You are using Server.MapPath twice on the same string. Please remove it from anyone location so that the path mapped according to server may not be mapped again.
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
FileUploadControl.SaveAs(Server.MapPath(fileuploadpath));
You may do it like this...
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
FileUploadControl.SaveAs(fileuploadpath);
you are getting this error as the first character in you path is ~. What you have to do is try removing this character and then save the string in your database.
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath.Substring(1,fileuploadpath.Length - 1) + "')", cn);
its ok managed to do it myself with this:
//string filename = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}

Categories