I am trying to display my data on my website, using asp.net and c# but im getting this error, System.Data.SqlClient.SqlException: Incorrect syntax near '='. please help, i have double check my code but nothing seems to be wrong.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RDCINFOS"].ConnectionString);
SqlCommand cmd;
SqlDataReader dr;
string str;
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand cmd =new SqlCommand("select * from articles where id=" + Request.Params["x"], con);
cmd.CommandType = CommandType.Text;
con.Open();
dr= cmd.ExecuteReader();
while(dr.Read())
{
art.InnerHtml += "<br>" + dr["title"] + "</br><br>";
art.InnerHtml += dr["details"] + "<br>";
art.InnerHtml += "<img src=pict/" + dr["photo"] + " height=300 width=200/><br>";
}
}
first of all, check if Request.Params["x"] is not null, and then change
SqlCommand cmd =new SqlCommand("select * from articles where id=" + Request.Params["x"], con);
to
SqlCommand cmd =new SqlCommand("select * from articles where id=#id", con);
cmd.Parameters.AddWithValue("#id", Request.Params["x"]);
Request.Params["x"] possible empty, null or other type than id column in database
Related
I am trying to have the item selected from the combo box (Site PSI) auto-populate all the textboxes to the right. I have scoured the web and there is some data source selections and auotocomplete sections but they are not working. I have tried several steps that were resolved with a similar issue on this website but it is not working. Here is my code. the combobox is called cmbSitePSI and the text boxes txtSiteName, txtSiteLName, etc...I was able to autopopulate them from a grid but I am not using a grid. Please help, thank you so much in advance.
con.Open();
SqlDataAdapter da = new SqlDataAdapter(#"Select * from Site order by SitePSI", con);
DataTable dt = new DataTable();
da.Fill(dt);
SqlCommand cmd = new SqlCommand("Select SiteName, SiteLongName, SiteAddress1, SiteAddress2, SiteAddress3, SiteCity, SiteState, SiteZipCode, SiteCountry, " +
"SiteOperationsRegion from Site where SitePSI = '" + cmbSitePSI.Text + "'", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#SitePSI", int.Parse(cmbSitePSI.Text));
SqlDataReader dr = cmd.ExecuteReader();
dt1.Load(dr);
UPDATE
I have tried using this method but I have not been successful. I get squiggilies on these lines string sSiteName = r.GetString("SiteName");
private void CmbSitePSI_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter da2 = new SqlDataAdapter(#"Select * from Site where SitePSI = '" + cmbSitePSI + "'", con);
string constring = "Data Source=*********;Initial Catalog=DIETS;Integrated Security=True";
string Query = "Select * from Site where SitePSI = '" + cmbSitePSI.Text + "' ;";
SqlConnection condata = new SqlConnection(constring);
SqlCommand cmddata = new SqlCommand(Query, condata);
SqlDataReader r;
try
{
condata.Open();
r = cmddata.ExecuteReader();
while (r.Read())
{
string sSiteName = r.GetString("SiteName");
string sSiteLongName = r.GetString("SiteLongName");
txtSiteName.Text = sSiteName;
txtSiteLName.Text = sSiteLongName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I want to connect to my GuvenliBilgisayarim database. But baglanti is null - why ?
My code is:
SqlConnection baglanti = new SqlConnection("Data Source=DILEKZ\\SQLEXPRESS;Initial Catalog=GuvenliBilgisayarim;Integrated Security=True");
private void btn_giris_Click(object sender, EventArgs e)
{
baglanti.Open();
SqlCommand komut = new SqlCommand("select * from Login where kullanici_adi='" + txt_kulAdi.Text + " and kullanici_sifre=" + txt_sifre.Text +"',baglanti");
komut.Connection = baglanti;
SqlDataReader dr = komut.ExecuteReader();
if (dr.Read())
{
Rapor rpr = new Rapor();
rpr.Show();
}
else
{
MessageBox.Show("Kullanıcı adı veya şifre yanlış");
}
dr.Close();
}
Your SqlCommand's Text is invalid. The correct is (notice to the quotes '"):
SqlCommand komut = new SqlCommand("select * from Login where kullanici_adi='" + txt_kulAdi.Text + "'" +
" and kullanici_sifre='" + txt_sifre.Text + "'",baglanti);
However this kind of string concatenation is open for SQL injection. Try parameterized queries instead. Something like this:
SqlCommand komut = new SqlCommand("select * from Login where kullanici_adi=#kulAdi" +
" and kullanici_sifre=#sifre",baglanti);
komut.Parameters.AddWithValue("#kulAdi",txt_kulAdi.Text);
komut.Parameters.AddWithValue("#sifre",txt_sifre.Text);
Although specify the type directly and use the Value property is more better than AddWithValue:
komut.Parameters.Add("#kulAdi", SqlDbType.VarChar).Value = txt_kulAdi.Text;
Can we stop using AddWithValue() already?
public void buttonclick(object sender,eventArgs e)
{
SqlConnection con0 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con0.Open();
SqlCommand cmd0 = new SqlCommand("", con0);
con0.Close();
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con1.Open();
SqlCommand cmd3 = new SqlCommand("book_master_insert", con1);
cmd3.CommandType = CommandType.StoredProcedure;
SqlParameter customer_id = new SqlParameter("#customer_id", cust_id);
SqlParameter booking_from = new SqlParameter("#booking_from", ddlfrom.SelectedItem.Text);
SqlParameter booking_destination = new SqlParameter("#booking_destination", ddlto.SelectedItem.Text);
SqlParameter load_type = new SqlParameter("#load_type", ddlLoadtype.SelectedItem.Text);
SqlParameter no_of_containers = new SqlParameter("#no_of_containers", txt_no_of_container.Text);
SqlParameter booking_pickupdate = new SqlParameter("#booking_pickupdate", txt_date.Text);
SqlParameter booking_pickuptime = new SqlParameter("#booking_pickuptime", txt_time.Text);
SqlParameter booking_createdate = new SqlParameter("#booking_createdate", localDate);
cmd3.Parameters.Add(customer_id);
cmd3.Parameters.Add(booking_createdate);
cmd3.Parameters.Add(booking_from);
cmd3.Parameters.Add(booking_destination);
cmd3.Parameters.Add(load_type);
cmd3.Parameters.Add(no_of_containers);
cmd3.Parameters.Add(booking_pickupdate);
cmd3.Parameters.Add(booking_pickuptime);
cmd3.ExecuteNonQuery();
con1.Close();
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con2.Open();
SqlCommand cmd2 = new SqlCommand("select booking_ID from booking_master where customer_id='"+cust_id+"' and booking_from='" + ddlfrom.SelectedItem.Text + "'and booking_destination='" + ddlto.SelectedItem.Text + "' and load_type='" + ddlLoadtype.SelectedValue + "' and no_of_containers='" + txt_no_of_container.Text + "' and CAST (booking_pickupdate as date) ='" + txt_date.Text + "' and booking_pickuptime='" + txt_time.Text + "';", con2);
SqlDataReader rdr = cmd2.ExecuteReader();
while (rdr.Read())
{
booking_ID = rdr["booking_ID"].ToString();
}
con2.Close();
}
Because con0, con1, and con2 are the same, you can write it like this, and please make cmd2 like cmd3, using parameterized query:
using (var conn = new SqlConnection("...Connection String..."))
{
conn.Open();
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
// Query1
cmd.CommandText = "...Query1...";
cmd.ExecuteNonQuery();
// Query2
cmd.CommandText = "...Query2...";
cmd.ExecuteReader();
}
}
Talking about efficiency first what are you trying to do?
System.Data.SqlClient ( ADO.Net ) re-use connection pooling if it detects new connection is same with the first connection made base on it connectionstring.
Calling multiple SqlConnection doesn't matter as long as you close and dispose it after use. Much better if you wrap it with using() {} statement, but keep in mind that it depend on what you are trying to do or what you requirement is. Open/Close of connection is much cheaper than hold open connection for long time. If you can re-use connection do it like what #x... answers.
It is nothing to do with efficiency but you should AVOID appending user input value in you SQL query. This lead to SQL injection and exploitation like what #mar_s said. Alternatively you can use cmd.Parameters.AddWithValue("#Name", "Bob"); for your safety.
Note : I haven't tested the code :
public void buttonclick(object sender,eventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["BUM"].ConnectionString;
using(SqlConnection con0 = new SqlConnection(connectionString))
{
con0.Open();
using(SqlCommand cmd = new SqlCommand("book_master_insert", con0))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#customer_id", cust_id);
cmd.Parameters.AddWithValue("#booking_from", ddlfrom.SelectedItem.Text);
cmd.Parameters.AddWithValue("#booking_destination", ddlto.SelectedItem.Text);
cmd.Parameters.AddWithValue("#load_type", ddlLoadtype.SelectedItem.Text);
cmd.Parameters.AddWithValue("#no_of_containers", txt_no_of_container.Text);
cmd.Parameters.AddWithValue("#booking_pickupdate", txt_date.Text);
cmd.Parameters.AddWithValue("#booking_pickuptime", txt_time.Text);
cmd.Parameters.AddWithValue("#booking_createdate", localDate);
cmd.ExecuteNonQuery();
// This is a BAD idea and you should replace this using parametrized queries
using(SqlCommand cmd2 = new SqlCommand("select booking_ID from booking_master where customer_id='"+cust_id+"' and booking_from='" + ddlfrom.SelectedItem.Text + "'and booking_destination='" + ddlto.SelectedItem.Text + "' and load_type='" + ddlLoadtype.SelectedValue + "' and no_of_containers='" + txt_no_of_container.Text + "' and CAST (booking_pickupdate as date) ='" + txt_date.Text + "' and booking_pickuptime='" + txt_time.Text + "';", con2))
{
using(SqlDataReader rdr = cmd2.ExecuteReader())
{
while (rdr.Read())
{
booking_ID = rdr["booking_ID"].ToString();
}
}
}
}
}
}
I have added some data from an Excel spreadsheet to a DataGridView.
I am using this code to save the data to a database in SQL Server.
Country and Currency are of type VARCHAR and rate is Float. The data is successfully added but I have an error message from the SqlCommand line.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=NIFAL;Initial Catalog=Currency;Integrated Security=True;");
foreach (DataGridViewRow Row in dataGridView1.Rows)
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO CurrencyTable(Country, Currency, Rate) VALUES('" + Row.Cells[0].Value.ToString()
+ "', '" + Row.Cells[1].Value.ToString() + "', '" + Row.Cells[2].Value.ToString() + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
Sanitizing input is important, and you probably has some error in your input. I would try and get the error messages listed, here is sample code that uses a "using" statment, parameters and sends the error to the trace listener(s)
using (var con = new SqlConnection("Data Source=NIFAL;Initial Catalog=Currency;Integrated Security=True;"))
{
con.Open();
foreach (var Row in dataGridView1.Rows)
{
var cmd = new SqlCommand("INSERT INTO CurrencyTable(Country, Currency, Rate) VALUES(#country, #currency, #rate)",con);
cmd.Parameters.Add("#country", SqlDbType.VarChar, 20).Value = Row.Cells[0].Value.ToString();
cmd.Parameters.Add("#currency", SqlDbType.VarChar, 20).Value = Row.Cells[1].Value.ToString();
cmd.Parameters.Add("#rate", SqlDbType.Float).Value = Row.Cells[2].Value.ToString();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception err)
{
//You should here mark the row that has an error and output the error message
Row.Cells[3].Value = err.Message;
}
}
}
I failed to get the correct result with this code in Form2:
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * From udbTable Where Username Like '" + f1.textBox1.Text + "%'", conn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
label5.Text = reader["Username"].ToString();
}
conn.Close();
I have 3 samples data in the table, but i'm always getting the same result which is the first entry of the database. Whenever i input the last entry or second entry in the textbox1.Text, i still getting the first entry.
textbox1.Text is from Form1, and i set it's property Modification to Public.
label5.text is the output.
try this fix
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection=conn;
command.CommandText = "Select * From udbTable Where Username Like ?";
cmd.Parameters.Add("#Username",OleDbType.VarChar);
cmd.Parameters["#Username"].Value=f1.textBox1.Text;
OleDbDataReader reader = cmd.ExecuteReader();