ASP.NET is not sending a command to a SQL server - c#

I have been assigned to create a website for a club at my school at kmhsmc.somee.com. I choose ASP for the language and I am having an issue with a sql function. If you go to the website above and click on join current liveclub session and fill in a bunch of junk in the textboxes at the top and hit join, it throws a SQL exception. here is the code:
UName = TextBox1.Text;
CompN = TextBox2.Text;
TMin = TextBox3.Text;
Name = TextBox4.Text;
TextBox1.Visible = false;
TextBox2.Visible = false;
TextBox3.Visible = false;
TextBox4.Visible = false;
string sql = "INSERT INTO table_name values (" + Name + "," + UName + "," + CompN + "," + TMin + "," + "NA" + "," + 0 + ")";
conn.Open();
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch
{
Response.Write("<script>alert('SQL error: try again later')</script>");
}
finally
{
conn.Close();
}
And for anyone who asks, I am 110% sure it is not the connection string because it works just fine on the calender page of the site.
Here is some other relevant information about this project:
I am doing it in C# and HTML ONLY (CSS and other designing things will be done by someone else later)
The server uses SQL server 2012

Problem : you are not enclosing the String types VARCHAR,NVARCHAR columns inside single quotes.
Solution : you need to enclose the String types inside single quotes.
Try This:
sqlCmd.CommandText = "INSERT INTO tablename(name) VALUES('yourname');
Suggestion : You should use Parameterised queries to avoid SQL injection attacks.
Complete Code: using parameterised sql queries
string sql = "INSERT INTO table_name values (#Name,#UName,#CompN,#TMin,#value1,#value2)";
conn.Open();
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Name",Name);
cmd.Parameters.AddWithValue("#UName",UName);
cmd.Parameters.AddWithValue("#CompN",CompN);
cmd.Parameters.AddWithValue("#TMin",TMin);
cmd.Parameters.AddWithValue("#value1","NA");
cmd.Parameters.AddWithValue("#value2",0);
cmd.ExecuteNonQuery();
}

your sql string is wrong.
UName = TextBox1.Text;
CompN = TextBox2.Text;
TMin = TextBox3.Text;
Name = TextBox4.Text;
TextBox1.Visible = false;
TextBox2.Visible = false;
TextBox3.Visible = false;
TextBox4.Visible = false;
string sql = "INSERT INTO table_name values ('" + Name + "','" + UName + "','" + CompN + "','" + TMin + "','NA', 0 )";
conn.Open();
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch
{
Response.Write( "<script>alert( 'SQL error: try again later' )</script>" );
}
finally
{
conn.Close();
}

Related

run SQL Commands from text box value

i create small project that read data from sqlserver then insert into mysql table.
i want to users write SQL and mysql command into textbox.
here is my problem, when i run project the field that inserted into mysql table are: myReader["STableName"].ToString()
like this picture:
connections are fine, here is my code:
string address;
string username;
string password;
string database;
address = textBox1.Text;
username = textBox2.Text;
password = textBox3.Text;
database = textBox4.Text;
//MySql
string mysqladdress;
string mysqlusername;
string mysqlpassword;
string mysqldatabase;
mysqladdress = textBox7.Text;
mysqlusername = textBox8.Text;
mysqlpassword = textBox9.Text;
mysqldatabase = textBox10.Text;
//SQLCode
string sqlcmnd1;
string sqlcmnd2;
sqlcmnd1 = textBox5.Text;
sqlcmnd2 = textBox6.Text;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=" + address + ";" +
"Initial Catalog=" + database + ";" +
"User id=" + username + ";" +
"Password=" + password + ";";
try
{
conn.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(sqlcmnd1, conn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
string connectionString = #"server=" + mysqladdress + ";" + "username=" + mysqlusername + ";" + "password=" + mysqlpassword + ";" + "database=" + mysqldatabase + "";
MySqlConnection connection = null;
MySqlDataReader reader = null;
try
{
connection = new MySqlConnection(connectionString);
connection.Open();
string stm = sqlcmnd2;//here is my problem
MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
dataAdapter.SelectCommand = new MySqlCommand(stm, connection);
DataTable table = new DataTable();
dataAdapter.Fill(table);
}
sqlcmnd2:
INSERT INTO test (CusCode,STableName,Date,ModdatZaman) VALUES ('" + myReader["CusCode"].ToString() + "','" + myReader["STableName"].ToString() + "','" + myReader["Date"].ToString() + "','" + myReader["ModdatZaman"].ToString() + "')
sqlcmnd1:
SELECT * FROM __TempUserCompRep__
Text from a textbox is considered as a full string it not replace the actual value of the variable .
You need to use prepared statement for that.
In textbox6 you write the command like this :
INSERT INTO test (CusCode,STableName,Date,ModdatZaman) VALUES (#CusCode,#STableName,#Date,#ModdatZaman)
After that in code, bind the parameter with variable from you actually want to take value.
For example:
MySqlConnection con = null;
try
{
string myConnectionString = "server=localhost;database=test;uid=root;pwd=root;";
con = new MySqlConnection(myConnectionString);
string CmdString = textBox6.Text.ToString();
MySqlCommand cmd = new MySqlCommand(CmdString, con);
cmd.Parameters.Add("#CusCode", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#STableName", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#Date", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#ModdatZaman", MySqlDbType.VarChar, 50);
cmd.Parameters["#CusCode"].Value = myReader["CusCode"].ToString();
cmd.Parameters["#STableName"].Value = myReader["STableName"].ToString();
cmd.Parameters["#Date"].Value = myReader["Date"].ToString();
cmd.Parameters["#ModdatZaman"].Value = myReader["ModdatZaman"].ToString();
con.Open();
int RowsAffected = cmd.ExecuteNonQuery();
if (RowsAffected > 0)
{
MessageBox.Show("Insert Query sucessfully!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con != null && con.State == ConnectionState.Open)
{
con.Close();
}
}
Note: I consider all four columns are varchar type in the database. you modify it according to your requirement
Hello Muhammad i would suggest you not to execute the sql commands from text box as there is a high chance of sql injection attacks , try to avoid as much you can , its a suggestion for more secured application

how to insert date(long format) into access database using datetimepicker in c# ? (error is in date part only)

Error image is here
the error is in query line , its shows syntax error
try
{
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
command.CommandText = "insert into client_table(CLIENT, DATE,BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #" + dat.ToLongDateString() + "# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
this.Hide();
employee_form f1 = new employee_form("");
f1.ShowDialog();
}
thank you in advance
In Access, dates are delimited by #, not '. Also, Access does not recognize the long date format. But dates are not stored in any format so no worries, change it to:
... + "', #" + dat.ToString() + "# ...etc.
Although if you do not parameterize your query serious damage or data exposure can be done through SQL Injection because someone could type in a SQL statement into one of those textboxes that you are implicitly trusting.
Working example:
class Program
{
static void Main(string[] args)
{
System.Data.OleDb.OleDbConnectionStringBuilder bldr = new System.Data.OleDb.OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new System.Data.OleDb.OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#" + DateTime.Now.ToString() + "#)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
}
Update
However, you want to do something more like this which uses Parameters to protect against SQL Injection which is extremely easy to exploit so do not think that you don't really need to worry about it:
static void Main(string[] args)
{
OleDbConnectionStringBuilder bldr = new OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
OleDbParameter dobParam = new OleDbParameter("#dob", OleDbType.Date);
dobParam.Value = DateTime.Now;
cmd.Parameters.Add(dobParam);
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#dob)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
//code to write date in the access table.
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
//MessageBox.Show(dat.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
//command.CommandText = "insert into client_table(DATEE) values( '"dat.ToShortDateString()+"')";
command.CommandText = "insert into client_table (CLIENT, DATEE, BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #"+dat.ToShortDateString()+"# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
//New code for receiving the date between two range of dates
try
{
DateTime dat = this.dateTimePicker1.Value.Date;
DateTime dat2 = this.dateTimePicker2.Value.Date;
// MessageBox.Show(dat.ToShortDateString() + " " + dat2.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
string query;
query = "select * from client_table Where DATEE Between #" + dat.ToLongDateString() +"# and #" + dat2.ToLongDateString() + "# ";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection1.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
Thank you all of you for the support.

UPDATE STATEMENT 2 tables c#

my problem is that i tried all kind of solutions but it doesnt update my table here is my code behind of the button_click update:
protected void Button2_Click(object sender, EventArgs e)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("Files/" + fileName));
SqlConnection cnx = new SqlConnection();
cnx.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["str"].ConnectionString;
SqlCommand cmd = new SqlCommand("Update Appel_offre set Titre_ao='" + TextBox4.Text + "',Description_ao='" + TextBox5.Text + "',Cout='" + TextBox6.Text + "',Type='" + DropDownList3.Text + "',Date='" + TextBox8.Text + "',Echeance='" + TextBox9.Text + "',Reference='" + TextBox7.Text + "',Piece_jointe='" + "Files/" + fileName + "',filename='" + fileName + "' where Id_ao = '" + Session["Id_ao"] + "' ", cnx);
SqlCommand cmd1 = new SqlCommand("Update Lot set Description=#desc,Reference=#ref,Type=#type where Titre = '" + Dropdownlst.SelectedItem.Value + "'",cnx);
cnx.Open();
cmd1.Parameters.AddWithValue("#desc", TextBox2.Text );
cmd1.Parameters.AddWithValue("#ref", TextBox3.Text );
cmd1.Parameters.AddWithValue("#type", DropDownList2.Text );
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
cnx.Close();
if (IsPostBack)
{
conff.Visible = true;
}
}
It's difficult to tell what's wrong here but I will gry to improve your code.
Maybe it also fixes the issue.
Use verbatim string literals, that makes your SQL query much better to read
Use the using statement to ensure that everything gets disposed properly
Don't use string concatenation to build your SQL query but SqlParameter, without exception. That prevents you from SQL injection and other issues.
Use not AddWithvalue but Add with the correct SqlDbType, otherwise the database makes guesses about the type of your parameter.
Pass the correct type and don't let the database cast your parameters, that also validates invalid input(f.e. incorrect date)
Code:
string updateApple = #"Update Appel_offre Set
Titre_ao = #Titre_ao,
Description_ao = #Description_ao,
Cout = #Cout,
Type = #Type,
Date = #Date,
Echeance = #Echeance,
Reference = #Reference,
Piece_jointe = #Piece_jointe,
filename = #filename
where Id_ao = #Id_ao;";
string updateLot = #"Update Lot Set
Description = #Description,
Reference = #Cout,
Type = #Type
where Titre = #Titre;";
using (var cnx = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["str"].ConnectionString))
using(var cmd_UpdateApple = new SqlCommand(updateApple, cnx))
using (var cmd_UpdateLot = new SqlCommand(updateLot, cnx))
{
cmd_UpdateApple.Parameters.Add("#Titre_ao", SqlDbType.VarChar).Value = TextBox4.Text;
cmd_UpdateApple.Parameters.Add("#Description_ao", SqlDbType.VarChar).Value = TextBox5.Text;
// ...
cmd_UpdateApple.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.Parse(TextBox8.Text);
// ...
cnx.Open();
int updatedAppels = cmd_UpdateApple.ExecuteNonQuery();
cmd_UpdateLot.Parameters.Add("#Description", SqlDbType.VarChar).Value = TextBox2.Text.Text;
// ...
cmd_UpdateLot.Parameters.Add("#Titre", SqlDbType.VarChar).Value = Dropdownlst.SelectedItem.Value;
int updatedLot = cmd_UpdateApple.ExecuteNonQuery();
}
I've used DateTime.Parse, use DateTime.TryParse if the format can be invalid.

my update c# code is not working,can i update two relational table at once?

i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here

How can i set a CommandText to my Search Button?

I'm trying to make a search button that when i enter an ID to a Textbox and press it , it goes to my private SQL server database and get the data row referred to that ID , But The exception handler brings me error because of my wrong CommandText .. Here is my Code
private void SearchBtn_Click(object sender, EventArgs e)
{
cn.ConnectionString = Properties.Settings.Default.ConStr;
if (ID.Text == "")
{
MessageBox.Show("Please Enter The ID you would like to search");
}
else
{
SqlCommand com = new SqlCommand();
cn.Open();
SqlParameter user = new SqlParameter("#ID", SqlDbType.Int);
SqlParameter FN = new SqlParameter("#First_Name",SqlDbType.NChar);
SqlParameter LN = new SqlParameter("#Last_Name", SqlDbType.VarChar);
SqlParameter Jb = new SqlParameter("#Job", SqlDbType.VarChar);
SqlParameter Ag = new SqlParameter("#Age", SqlDbType.VarChar);
SqlParameter ph = new SqlParameter("#Phone", SqlDbType.VarChar);
com.Parameters.Add(user);
com.Parameters.Add(FN);
com.Parameters.Add(LN);
com.Parameters.Add(Jb);
com.Parameters.Add(Ag);
com.Parameters.Add(ph);
com.Connection = cn;
Here is my Error :
*com.CommandText = "Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList) ";*
user.Direction = ParameterDirection.Input;
FN.Direction = ParameterDirection.Output;
LN.Direction = ParameterDirection.Output;
Jb.Direction = ParameterDirection.Output;
Ag.Direction = ParameterDirection.Output;
ph.Direction = ParameterDirection.Output;
FN.Size = 10;
LN.Size = 10;
Jb.Size = 10;
Ag.Size = 10;
ph.Size = 10;
user.Value = Convert.ToInt32(ID.Text);
try
{
com.ExecuteNonQuery();
FirstName.Text = FN.Value.ToString();
LastName.Text = LN.Value.ToString();
Job.Text = Jb.Value.ToString();
Age.Text = Ag.Value.ToString();
Phone.Text = ph.Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
I'm Using Visual Studio 2012 .
Thanks in Advance .
"Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList)"
doesn't really look like SQL. Also I'm not quite sure why you're setting loads of parameters you're not using.
Maybe you meant something like
com.CommandText = "SELECT First_Name, Last_Name, Job, Age, Phone FROM MyList WHERE ID=#Id";
com.Parameters.AddWithValue("#Id", ID.Text);
Furthermore if that's your intention, then ExecuteNonQuery is wrong as that's for INSERT, UPDATE and other things that don't return a result.
Command text should be like
com.CommandText = "SELECT First_Name, Last_Name, Job, Age, Phone FROM MyList WHERE ....";
Remove most of your parameters, leave only input ones.
Instead of com.ExecuteNonQuery() use: SqlDataReader reader = command.ExecuteReader(); and using it read your data. Example article is here
Firstly:
"Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList)"
Doesn't look like valid SQL to me.
I think you're looking to do something like this:
using (SqlConnection myConnection = new SqlConnection(connString))
{
string oString = " SELECT * from MyList WHERE (id = #id)";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.Add(new SqlParameter("#id", ID.Text));
myConnection.Open();
string name="";
string lastname ="";
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
name = oReader["name"].ToString(); // replace "name" with the name of the column you want
lastname = oReader["lastname"].ToString();
}
}
myConnection.Close();
return name + lastname;
You can use these values to set the text in your textboxes on your form:
YourNameTextbox.Text = name;
.. etc

Categories