Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
protected void Button1_Click(object sender, EventArgs e)
{
int anInteger;
anInteger = Convert.ToInt32(txtmarks.Text);
anInteger = int.Parse(txtmarks.Text);
if (anInteger >= 60)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString =" Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\sakshi\\Documents\\m.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adp = new OleDbDataAdapter();
OleDbDataReader rd;
cmd = new OleDbCommand("insert into student(fname,fmarks,fboard)values('" + txtname.Text + "','" + txtmarks.Text + "','" + ddlbrd.SelectedItem.ToString() + "'),con");
cmd.ExecuteNonQuery();
}
else
{
Response.Write("u are not elligible");
}
As mentioned in the comments on your question, you should look into parameterized queries, but right off it looks like you are not calling the OleDbCommand constructor properly.
You have:
cmd = new OleDbCommand("insert into student(fname,fmarks,fboard)values('" + txtname.Text + "','" + txtmarks.Text + "','" + ddlbrd.SelectedItem.ToString() + "'),con");
Which looks like you closed your string in the wrong place. Try the following instead:
cmd = new OleDbCommand("insert into student(fname,fmarks,fboard)values('" + txtname.Text + "','" + txtmarks.Text + "','" + ddlbrd.SelectedItem.ToString() + "')",con);
I would change my code to something like the following instead:
OleDbCommand cmd = new OleDbCommand(
"insert into student(fname,fmarks,fboard)values(#fname,#fmarks,#fboard);",
con
);
OleDbParameter parmName = cmd.CreateParameter();
parmName.ParameterName = "#fname";
parmName.OleDbType = OleDbType.VarChar;
parmName.Value = txtname.Text;
cmd.Parameters.Add(parmName);
OleDbParameter parmMarks = cmd.CreateParameter();
parmMarks.ParameterName = "#fmarks";
parmMarks.OleDbType = OleDbType.VarChar;
parmMarks.Value = txtmarks.Text;
cmd.Parameters.Add(parmMarks);
OleDbParameter parmBoard = cmd.CreateParameter();
parmBoard.ParameterName = "#fboard";
parmBoard.OleDbType = OleDbType.VarChar;
parmBoard.Value = ddlbrd.SelectedItem.ToString();
cmd.Parameters.Add(parmBoard);
Based on not initialised error, looks like you add con as a part of your sql command in your OleDbCommand constructor, not as a second parameter.
Change your
+ "'),con");
to
+ "')", con);
But I suggest a few things more;
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Delete your OleDbDataAdapter and OleDbDataReader definitions since you never use them.
Delete your anInteger = Convert.ToInt32(txtmarks.Text) line because it is identical with anInteger = int.Parse(txtmarks.Text) line.
Use using statement to dispose your connection and command automatically.
Open your connection just before when you execute your command. Move your con.Open() line just before your cmd.ExecuteNonQuery() line.
if(int.Parse(txtmarks.Text) > 60)
{
using(var con = new OleDbConneciton("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\sakshi\\Documents\\m.accdb"))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"insert into student(fname,fmarks,fboard)
values(#fname, #fmarks, #fboard)";
// Add your parameters and their values with Add method and specifing their types
con.Open();
cmd.ExecuteNonQuery();
}
}
Related
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 am implementing an online voting system for my school-project.
After the voter's log-in, i want to display their name, and ID in the label control at the content body. I try to use SESSION to store the voter's username in the log-in page but I'm not sure of my syntax because nothings happen.
I want to know the other way of retrieving a data from database! Please teach me.
public void GetInformation()
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM tblUsers WHERE voter_name = '" + Session["VotersID"] + "'";
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
lblVoterName.Text = reader["usr_FirstN"].ToString() + " " + reader["usr_LastN"].ToString();
}
}
Please Help Me. Thanks! -
#Honey Maglangit , what you use is PARAMETER not SESSION.
Response.Redirect("VoterPage.aspx?VotersID="+VoterUsername.Text);
So, you should get your VotersID by this way:
public void GetInformation()
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM tblUsers WHERE voter_name = '" + Request.QueryString["VotersID"].ToString() + "'";
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
lblVoterName.Text = reader["usr_FirstN"].ToString() + " " + reader["usr_LastN"].ToString();
}
}
Try it again.
You can use LogonUserIdentity as follow
if (Request.LogonUserIdentity.IsAuthenticated)
lblName.Text = Request.LogonUserIdentity.Name;
just add this namespace:
using Microsoft.AspNet.Identity;
then you can get LoggedInUserId by:
User.Identity.GetUserId();
Or
HttpContext.Current.User.Identity.GetUserId();
So you don't need to use session to keep UserId.
Also you can create Custom Identity and instead of save Username in Name property, storing custom string Store User Data in ASP.NET Identity
get session data and send to one page(register.aspx) to another page(user_home.aspx)
Session["remail2"] = txtemailsignin.Text;
Server.Transfer("user_home.aspx", true);
display the user-information after logging
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["socailweb"].ConnectionString);
string sql = "select * from tblUsers where remail='" + Session["remail2"] + "'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sqldr = cmd.ExecuteReader();
if (sqldr.Read() == true)
{
lblVotersID.Text = sqldr.GetValue(2).ToString();
lblVoterName.Text = sqldr.GetValue(3).ToString();
}
sqldr.Close();
con.Close();
I'm having trouble with a SQL query:
using (SqlConnection conn = new SqlConnection("user id=user;" + "password=pass;" + "server=server;" + "database=db;"))
{
using (SqlCommand comm = new SqlCommand(#"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'"))
{
conn.Open();
comm.Connection = conn;
MessageBox.Show("TEST: {0}", Convert.ToString((int)comm.ExecuteScalar()));
}
}
I'm expecting to get an int in the message box conveying the number of rows that BolagsID occurs in. But I get 0 every time. I've tried the query in SQL Server Management Studio and it works fine there. What am I doing wrong/missing?
EDIT:
This works, but now I don't know how to parameterize the values:
string query = #"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = " + BolagsID;
ADODB.Connection conn2 = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset();
string strConn = "Provider=...;Data Source=...;Database=...;User Id=...;Password=...";
conn2.Open(strConn);
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic;
rs.Open(query, conn2);
if (rs.Fields[0].Value > 0)
...stuff...
Like others are saying, parameters are a good idea. Here's something to get you started:
string query = #"SELECT Count(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = #BolagsID";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#BolagsID", SqlDbType.NVarChar).Value = BolagsID;
conn.Open();
MessageBox.Show("TEST: {0}", Convert.ToString((int)cmd.ExecuteScalar()));
conn.Close();
}
Basically a 0 is returned if there is an error in your query, so even though SSMS is smart enough to resolve it, the sql command isn't.
A quick way to make sure that everything else is working okay is to change the query to just "SELECT Count(*) FROM [CompaniesDB].[dbo].[Companies]". If that doesn't work then the issue could lie with your database connection (permissions?) or something else.
Try assigning SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'" to a string str as follows
string str =#"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'";
using (SqlConnection conn = new SqlConnection("user id=user;" + "password=pass;" + "server=server;" + "database=db;"))
{
using (SqlCommand comm = new SqlCommand(str))
{
conn.Open();
comm.Connection = conn;
MessageBox.Show("TEST: {0}", Convert.ToString((int)comm.ExecuteScalar()));
}
}
Then do a watch/quickwatch on str's value to get the exact query that is getting run and then run the same query in Sql Managment studio. If you get 0 in Sql Management Studio as well, then the problem is that the data is just not there.
I tried a lot of stuff before trying out a whole different approach. This gives me the result I want:
string query = #"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = " + BolagsID;
ADODB.Connection conn2 = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset();
string strConn = "Provider=...;Data Source=...;Database=...;User Id=...;Password=...";
conn2.Open(strConn);
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic;
rs.Open(query, conn2);
if (rs.Fields[0].Value > 0)
...stuff...
Note that both connection and record set are closed outside of this code snippet.
I'm trying to update my database i.e. a MS Access file, I want to update my table by taking the values from the textboxes but I'm not able to write a proper query.
Can anyone please help me to write a proper update query?
string strconn4 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|pay.accdb";
OleDbConnection sqlconn4 = new OleDbConnection(strconn4);
sqlconn4.Open();
OleDbCommand ocmd = new OleDbCommand("UPDATE fees SET fname=" + Convert.ToString(textBox2.Text) + ",lname=" + Convert.ToString(textBox3.Text) + ",amtpayd=" + Convert.ToString(textBox4.Text) + ",amtleft=" + Convert.ToString(textBox5.Text) + ",disc=" + Convert.ToString(textBox6.Text) + ",pdate=" + Convert.ToString(dateTimePicker3.Text) + ",rdate=" + Convert.ToString(dateTimePicker1.Text) + ",WHERE memid=" + Convert.ToString(textBox1.Text), sqlconn4);
Your code is prone to SQL injection which is a very serious security problem!
You should use parameterized queries instead.
Some links on how build such queries including references and samples:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.aspx
http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access
https://stackoverflow.com/a/4589424/847363
http://social.msdn.microsoft.com/Forums/en/accessdev/thread/33f3f6bc-03b2-4f64-84ca-cef65bbc0eee
Like this
string sql=string.Format("UPDATE Table1 SET column1='{0}',column2='{1}' where id={2}",tbx1.text,tbx2.text,tbx3.text);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strconn4;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sql;
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();