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?
Related
I have to write the code which update a user's password. There must be entered a user's username (Brugernavn) , password (Adgangskode), new password and confirm password. The code is running, but UPDATE command does not update the password.
Until now, I have tried with this code (I know, that parametrized query should be used, but I don't have any idea about how to write such query, while this is combination of a SELECT and UPDATE statements):
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM dbo.Login_data WHERE Brugernavn='" + textBox1.Text + "' AND Adgangskode='" + textBox2.Text + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ErrorProvider errorProvider1 = new ErrorProvider();
errorProvider1.Clear();
if(dt.Rows[0][0].ToString() == "1")
{
if(textBox3.Text == textBox4.Text)
{
SqlDataAdapter sda1 = new SqlDataAdapter("UPDATE dbo.Login_data SET Adgangskode='" + textBox3.Text + "' WHERE Brugernavn='" + textBox1.Text + "' AND Adgangskode='" + textBox2.Text + "'", con);
MessageBox.Show("Adgangskoden er skiftet.", "Bekræftelse", MessageBoxButtons.OK);
}
else
{
errorProvider1.SetError(textBox3, "Adgangskode passer ikke");
errorProvider1.SetError(textBox4, "Adgangskode passer ikke");
}
}
else
{
errorProvider1.SetError(textBox1, "Du har tastet forkert brugernavn");
errorProvider1.SetError(textBox2, "Du har tastet forkert adgangskode");
}
}
The expected result is that password will be updated.
Instead of using a SqlAdapter for your update statement, create a new SqlCommand as you do for the Select statement. Then call the ExecuteNonQuery method on the SqlCommand object.
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
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 am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());
I need to be able to verify a username and password against a sql server and I need code for a C# forms application.
I have it setup with 2 textboxes (1 user and 1 pass) and then I have a login button.
SqlConnection UGIcon = new SqlConnection();
UGIcon.ConnectionString = "Data Source=HP-PC//localhost;Initial Catalog=UGI;Integrated Security=True";
UGIcon.Open();
string userText = textBox11.Text;
string passText = textBox12.Text;
SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword FROM LoginDetails WHERE stUsername='" + textBox11.Text + "' and stPassword='" + textBox12.Text + "'", UGIcon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if ( dt.Rows.Count > 0)
{
MessageBox.Show("Login Success!!");
cmd = new SqlCommand("SELECT stRole from LoginDetails where stUsername=#stUsername", UGIcon);
cmd.Parameters.AddWithValue("#stUsername",userText);
string role = cmd.ExecuteScalar().ToString();
MessageBox.Show(role);
UGIcon.Close();
}
else
{
MessageBox.Show("Access Denied!!");
UGIcon.Close();
}
I'm a real believer in using the "using" statements. You can also save yourself a 2nd query by asking for the stRole variable in the original query. The using blocks will automatically dispose of the objects, so when execution leaves this area, the objects will automatically be cleaned up.
using (SqlConnection UGIcon = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=UGI;Integrated Security=True"))
{
UGIcon.Open();
string userText = textBox11.Text;
string passText = textBox12.Text;
SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword, stRole FROM LoginDetails WHERE stUsername='" + userText + "' and stPassword='" + passText + "'", UGIcon);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
string role = rdr["stRole"].ToString();
MessageBox.Show(role);
}
}
else
{
MessageBox.Show("Access Denied!!");
}
}
}
Pls check this code
SqlConnection thisConnection = new
SqlConnection(#"Server=(local)\sqlexpress;Integrated Security=True;" +
"Database=northwind");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "Select count(*) from UserDetails
WHere UserName = "+txtUsername.text.trim().toLower() + " and Password = " +txtPassword.text.trim().toLower();
Object countResult = thisCommand.ExecuteScalar();
Console.WriteLine("Count of Customers = {0}", countResult);
thisConnection.Close();