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
Related
This is my code, and I want to be able to search for a name, and then pull from the database the name, status, member_id into the textboxes in my form.
I got the name to work but how do I get the other columns and parse the output into the textboxes with the additional columns (member_id, status)? Let's say the other textboxes have the standard name such as textbox2, 3, 4...
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
string sql1 = null;
SqlDataReader dataReader;
connetionString = "Data Source=......"
sql = "SELECT NAME FROM Test_Employee WHERE Name LIKE '" + textBox1.Text.ToString() + "%'";
connection = new SqlConnection(connetionString);
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
textBox9.Text = dataReader[0].ToString();
textBox7.Text = dataReader[0].ToString();
}
connection.Close();
}
Are the fields Member_Id and Status also in the table Test_Employee? You can add them in your Select statement and get them from your SqlReader, like the code below (assuming you are using c#7 and below). You may copy and paste this code.
var connectionString = "";
var sql = #"SELECT TOP 1 Name, Member_Id, Status
FROM Test_Employee
WHERE Name LIKE #name + '%'";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("name", SqlDbType.NVarChar, 100).Value = textBox1.Text.ToString();
connection.Open();
var reader = command.ExecuteReader();
if (reader.Read())
{
textBox9.Text = dataReader["Name"].ToString();
textBox7.Text = dataReader["Name"].ToString();
textBox2.Text = dataReader["Member_Id"].ToString();
textBox3.Text = dataReader["Status"].ToString();
}
}
You will notice that instead of including the Textbox1.Text's value in your Select statement, it is added as a parameter in the SQLCommand object's Parameters. In this way your query is protected from SQL Injection. If you want to learn more, you can search c# sqlcommand parameters and why it is very important to build data access code this way.
Also, notice that I added Top 1 in your Select statement, and instead of using while, I am using if. This is because a textbox can only hold 1 result at a time in a comprehensible way. If you meant to show multiple results clearly, you need to use a different control other than a TextBox.
The using statements allow you to dispose the connection, so you don't have to call connection.Close().
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], ...
I want to perform 2 queries in one button click. I tried the
string query = "first query";
query+="second query";
But this didn't work it shows error.
I have now created 2 separate connections like below:
try
{
SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
//open connection with database
conn1.Open();
//query to select all users with teh given username
SqlCommand com1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", conn1);
// comand.Parameters.AddWithValue("#id", iD);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute queries
com1.ExecuteNonQuery();
conn1.Close();
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise eshte 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com2 = new SqlCommand("insert into artikulli(path) values ('" + filename + "')", conn2);
//open connection with database
conn2.Open();
com2.ExecuteNonQuery();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni perzgjedhur asnje file');", true);
}
}
But the problem is that only the second query is performed and the firs is saved as null in database
In your case, there is no reason to open two connections. In addition, the C# language has evolved, so I recommend using the power given by the new language constructs (using, var).
Here is an improved version that should work assuming that the values you bind to your parameters are valid:
try
{
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString))
{
//open connection with database
connection.Open();
//query to select all users with teh given username
using(var command1 = new SqlCommand("insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)", connection))
{
command1.Parameters.AddWithValue("#tema", InputTitle.Value);
command1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
command1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
command1.Parameters.AddWithValue("#keywords", InputTags.Value);
//execute first query
command1.ExecuteNonQuery();
}
//build second query
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
using(SqlCommand command2 = new SqlCommand("insert into artikulli(path) values (#filename)", connection))
{
//add parameters
command2.Parameters.AddWithValue("#filename", filename);
//execute second query
command2.ExecuteNonQuery();
}
}
}
//TODO: add some exception handling
//simply wrapping code in a try block has no effect without a catch/finally
Try below code, No need to open the connection twice
string query1 = "insert into artikulli (tema,abstrakti, kategoria_id, keywords ) values (#tema, #abstrakti, #kategoria, #keywords)";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString);
SqlCommand com1= new SqlCommand(query1, conn);
com1.Parameters.AddWithValue("#tema", InputTitle.Value);
com1.Parameters.AddWithValue("#abstrakti", TextareaAbstract.Value);
com1.Parameters.AddWithValue("#kategoria", DropdownCategory.Value);
com1.Parameters.AddWithValue("#keywords", InputTags.Value);
string query2 = "insert into artikulli(path) values ('" + filename + "')", conn);
comm.ExecuteNonQuery();
comm.CommandText = query2;
comm.ExecuteScalar();
public string checkUsername(string username, string password)
{
string result = "invalid username/password";
string connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~\\myDB\\database.mdb");
string queryString = "SELECT * FROM Table WHERE [username]='" + username + "' AND [password]='" + password + "';";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = queryString;
OleDbDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
result = "";
}
}
finally
{
reader.Close();
connection.Close();
}
}
return result;
}
System.Data.OleDb.OleDbException: Data type mismatch in criteria expression.
pointing around this line:
OleDbDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
wanted to try:
cmd.Parameters.AddWithValue("#password", txtBoxPassword.Text);
but that "txtBoxPassword" doesnt exist in current context.
just learned c# for few months now but still need guidance.
The way you have your SQL statement, you are wide open for SQL injection. It should be parameterized as you were optionally shooting for... Put that as your statement.
SELECT * FROM Table WHERE [username]=#parmUserName AND [password]=#parmPassword
Then, add your parameters as you were going for, but you should probably clean them too for sanity purposes. Here, the inbound parameters of username, password are NOT the column names for the query. You are setting these VALUES into the parameter objects.
cmd.Parameters.AddWithValue ( "#parmUserName", username);
cmd.Parameters.AddWithValue ( "#parmPassword", password);
private void d_Load(object sender, EventArgs e)
{
string connstring = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\it155.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection conn = new SqlConnection(connstring);
try
{
conn.Open();
string snumber = txtSnumber.Text;
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber ='" + txtSnumber.Text + "'", conn);
}
catch (Exception)
{
}
}
given the start of the code which is written above, what i plan to do is to be able to log in using id number datatype varchar(11) in the sql database which was to be entered in the txtSnumber but aside that i cant figure out how to check whether the id number entered is correct or not and if it is correct, the information corresponding to that id number enetered is supposed to show in the their corresponding textboxes. please help me, thanks
Your sql statement is prone to SQL Injection. Is terrible practice to concatenate SQL like this. Instead do something like this:
string snumber = txtSnumber.Text;
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber =#User", conn);
get.Parameters.AddWithValue("#User",snumber);
Now, in order to check whether the record was found or not, you do this:
using(IDataReader reader = get.ExecuteReader())
{
if (reader.HasRows)
{
//information correct. Do something
}
}
You can check it by using a DataReader()
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber ='" + txtSnumber.Text + "'", conn);
SqlDataReader myReader = get.ExecuteReader();
if (myReader.HasRows)
{
MessageBox.Show("ID is valid");
while (myReader.Read())
//Do something here
}
else
MessageBox.Show("Given ID is Invalid.");
EDIT:
While calling ExecuteReader() method you put the following argument inside it, so that when ever you close the connection the datareader also automatically closes.
SqlDataReader myReader = get.ExecuteReader(CommandBehavior.CloseConnection);