protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
OleDbConnection con = new OleDbConnection(strConnString);
string strQuery = "INSERT INTO image([FileName],[FilePath],[AlbumName]) Values(#FN, #FP, #AN)";
OleDbCommand cmd = new OleDbCommand(strQuery);
cmd.Parameters.AddWithValue("#FN", FileName);
cmd.Parameters.AddWithValue("#FP", "images/" + FileName);
cmd.Parameters.AddWithValue("#AN", txtAlbumname.Text.ToString());
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string var = DropDownList1.SelectedItem.ToString();
txtAlbumname.Text = var.ToString();
}
}
I Have tried almost everything , but this error keeps on coming.
I have put on the brackets aswell incase of reserved words but still this error is showing
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
For Example
OleDbCommand command = new OleDbCommand(queryString, connection);
command.CommandText =
"SELECT CustomerID, CompanyName FROM Customers WHERE Country = ? AND City = ?";
command.Parameters.Add(parameters);
for (int j=0; j<parameters.Length; j++)
{
command.Parameters.Add(parameters[j]) ;
}
for reference ..
MSDN
IMAGE is a reserved word in Access SQL so to use it as a table name you must also enclose it in square brackets:
string strQuery = "INSERT INTO [image] ([FileName], ...
Related
I am trying to DELETE a record of Access Database using OleDbCommand class of Connected Architecture
using System.Data.OleDb;
using System.Data;
protected void Button2_Click(object sender, EventArgs e)
{
String x = "Connection String...";
OleDbConnection con = new OleDbConnection(x);
con.Open();
String query = "Delete FROM TB WHERE NO=#number";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#number", TextBox2.Text);
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label.Text = "Deleted successfully";
}
else
{
Label.Text = "Not Deleted";
}
con.Close();
}
Every time I try deleting record Else Condition is executed which is NOT DELETED.
Same problem with UPDATE query,
protected void Button3_Click(object sender, EventArgs e)
{
String x = "Connection String..";
OleDbConnection con = new OleDbConnection(x);
con.Open();
String query = "UPDATE TB SET NM = #name WHERE NO = #TextBox_NO";
OleDbCommand cmd = new OleDbCommand(query, con);
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label.Text = "Updated successfully";
}
else
{
Label.Text = "Not Updated";
}
con.Close();
}
INSERT query works perfectly fine.
Where am I doing wrong?
Preface: I know nothing of ASP.NET but I do know MS Access. And NO is a reserved word. Hence, if reserved words are used may result in unexpected answers or errors when referenced as fields.
To resolve, consider bracketing the NO column in both delete and update queries.
String query = "DELETE FROM TB WHERE [NO] = #number"
String query = "UPDATE TB SET NM = #name WHERE [NO] = #TextBox_NO"
I can confirm this solution as I just tested a NO vs [NO] column reference in a SQL query in MS Access 2013. The former returned zero records but latter returned correct records.
i think there is any datatype conversion error, that's why it's not deleting, and for the update case you just missed the parameter to pass #name,#TextBox_No
See here Why to use Add()
You need to change parameter passing method AddedWithValue() to Add()
Delete:
String query = "Delete FROM TB WHERE NO=#number";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.Add("#number", OleDbType.Numeric, 30).Value=TextBox2.Text;
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label.Text = "Deleted successfully";
}
else
{
Label.Text = "Not Deleted";
}
con.Close();
and for Update u missed the parameter to pass:
String x = "Connection String..";
OleDbConnection con = new OleDbConnection(x);
con.Open();
String query = "UPDATE TB SET NM = #name WHERE NO = #TextBox_NO";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.Add("#name ", OleDbType.VarChar, 200).Value=your_Name_Variable;//
cmd.Parameters.Add("#TextBox_NO", OleDbType.Numeric, 30).Value=Your_No_Variable;
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label.Text = "Updated successfully";
}
else
{
Label.Text = "Not Updated";
}
con.Close();
If it's not deleting any record that means int res = cmd.ExecuteNonQuery(); is returning 0 or no records deleted. Make sure that the condition in your WHERE clause WHERE NO=#number matches any record. To validate run a select along the line with the same condition
SELECT 1 FROM TB WHERE NO=#number
Also, try trimming the textbox data before punching as parameter like
cmd.Parameters.AddWithValue("#number", TextBox2.Text.Trim());
If NO is of type INT then covert it to integer before passing as parameter like
cmd.Parameters.AddWithValue("#number", Convert.ToInt32(TextBox2.Text.Trim()));
You can follow the same rules for your UPDATE case as well. Also, I don't see you are passing any parameter for your UPDATE query. Did you just skipped that in posted code?
String query = "UPDATE TB SET NM = #name WHERE NO = #TextBox_NO";
OleDbCommand cmd = new OleDbCommand(query, con);
Changes are not saved to the SQL database
Why would I want to use '#' in the sql statement instead of the way that I have the statement?
Code:
private void button_Save_Customer_Click(object sender, EventArgs e)
{
sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
string customer_Ship_ID = customer_Ship_IDTextBox.ToString();
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = customer_Ship_Address WHERE Customer_Ship_ID = customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Here you can check the MSDN reference for the update command.
Use parameters, Why?
Also check that you need to open and close the connection object, not the command.
In case you want to update the rows with the Customer_ID = "something" you could do like this:
The code (updated after your changes):
private void button_Save_Customer_Click(object sender, EventArgs e)
{
string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
int customer_Ship_ID;
if(int.TryParse(customer_Ship_IDTextBox.Text, out customer_Ship_ID))
{
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
// Customer_Ship: Database's table
// Customer_Ship_Address, Customer_Ship_ID: fields of your table in database
// #Customer_Ship_Address, #Customer_Ship_ID: parameters of the sqlcommand
// customer_Ship_ID, customer_Ship_Address: values of the parameters
string SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = #Customer_Ship_Address WHERE Customer_Ship_ID = #Customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
else
{
// The id of the textbox is not an integer...
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Seems like your syntax isn't correct. Here's the syntax for the Update:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
So, Update, what to set, and WHERE to set (which you seem to be missing).
For more, have a look here.
Check your update query
Change it like
string SQL = string.format("UPDATE Customer_Ship SET Customer_Ship_Address='{0}'",putUrVaue);
This piece of code works properly if there is any value without the apostrophe. But if the ddList.SelectedValue is, say, Women's day, it shows "Incorrect syntax near 's'. Unclosed quotation mark after the character string ''."
I tried the albumName.Replace but no luck so far.
protected void btnUpload_Click(object sender, EventArgs e)
{
string albumName = ddList.SelectedValue.ToString();
albumName.Replace("'", "''");
conn.Open();
SqlCommand command = new SqlCommand("select ID from Album where AlbumName = '" + albumName + "'", conn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
AlbmID = Int32.Parse((reader["ID"].ToString()));
}
reader.Close();
if (fileuploadimages.HasFile == false)
{ ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>alert('No File Uploaded.')</script>", false); }
else
{
//Get Filename from fileupload control
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
//Save images into SlideImages folder
fileuploadimages.SaveAs(Server.MapPath("Pictures/" + filename));
//Open the database connection
//Query to insert images name and Description into database
SqlCommand cmd = new SqlCommand("Insert into Images(ImagePath,Album_ID,ImageDesc) values(#ImagePath,#Album_ID,#ImageDesc)", conn);
//Passing parameters to query
cmd.Parameters.AddWithValue("#ImagePath", filename);
cmd.Parameters.AddWithValue("#Album_ID", AlbmID);
cmd.Parameters.AddWithValue("#ImageDesc", txtDescription.Text);
cmd.ExecuteNonQuery();
//Close dbconnection
conn.Close();
txtDescription.Text = "";
BindDataList();
}
}
SqlCommand command = new SqlCommand("select ID from Album where AlbumName = #name", conn);
command.Parameters.Add(new SqlParameter("#name", albumName));
.
.
.
In addition, you should wrap the connection,command, and reader objects in a using() {} construct to dispose of the resources in a timely fashion.
Use parameters like this whenever dynamic things are being put into a SQL string to avoid errors like this, as well as SQL injection attacks and other vulnerabilities.
In addition, you can rapidly replace parameters for executing multiple queries without having the rebuild the string.
.Replace("'",#"\'")
This will escape your single quote/apostrophe
I want this button's image use the image stored in database (image path)...
private void button15_Click(object sender, EventArgs e)
{
string a = button11.Text;
string connString = "Server=Localhost;Database=test;Uid=*****;password=*****;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = ("Select link from testtable where ID=" + a);
try
{
conn.Open();
}
catch (Exception ex)
{
//button11.Image = ex.ToString();
}
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
button11.Image = reader["path"].ToString();
}
}
I think the error lies in "reader["path"].ToString();" but I don't know what syntax to use.
If you stored the path to the image file on the disk in the path column, you should laod the image:
string path = (string)reader["path"];
button11.Image = Image.FromFile(path);
Side note: Never pass the values directly from a user input to a database query. It is vulnerable to sql injection attacks. Use parameters instead:
command.CommandText = "Select link from testtable where ID=#id";
command.Parameters.AddWithValue("#id", int.Parse(a));
try this:
while (reader.Read())
{
string path = reader.GetString(0);
button11.Image = Image.FromFile(path);
}
Try this: ( Written right to answer box, may be there are typo! )
private void button15_Click(object sender, EventArgs e)
{
string a = button11.Text;
string imagePath;
string connString = "Server=Localhost;Database=test;Uid=root;password=root;";
using(MySqlConnection conn = new MySqlConnection(connString))
using(MySqlCommand command = conn.CreateCommand())
{
command.CommandText = "Select link from testtable where ID=#id";
command.Parameters.AddWithValue("#id", int.Parse(a));
try
{
conn.Open();
imagePath= (string)command.ExecuteScalar();
}
catch (Exception ex)
{
//button11.Image = ex.ToString();
}
button11.Image = Image.FromFile(imagePath);
}
}
I created a simple asp.net form which allow users to view a list of dates for a training and register for that date , they enter their name and employeeid manually ( i dont want to allow dulpicate employe ids), so I need to figure out how to check this on c#..
code:
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
private void checkContraint()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select "; //NEED HELP HERE
}
private void InsertInfo()
{
var dateSelected = dpDate.SelectedItem.Value;
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT #Val1b+','+#Val1,#Val2,#Val3,#Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id =#training_id ";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Val1", txtName.Text);
cmd.Parameters.AddWithValue("#Val1b", txtLname.Text);
cmd.Parameters.AddWithValue("#Val2", txtDept.Text);
cmd.Parameters.AddWithValue("#Val3", txtTitle.Text);
cmd.Parameters.AddWithValue("#Val4", txtEmployeeID.Text);
//Parameter to pass for the select statement
cmd.Parameters.AddWithValue("#training_id", dateSelected);
cmd.CommandType = CommandType.Text;
//cmd.ExecuteNonQuery();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 1)
{
//Success notification // Sends user to redirect page
Response.Redirect(Button1.CommandArgument.ToString());
ClearForm();
}
else
{
//Error notification
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
checkContraint();
InsertInfo();
this way , your query will insert data only if not exists already
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT #Val1b+','+#Val1,#Val2,#Val3,#Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id =#training_id and not exists (select 1 from personTraining pp where pp .employeeid=#Val4) ";