com.Parameters.AddWithValue("#firstName", firstname.Text); - c#

I am trying to add data into table,but its not adding.I created conection, it should work.
protected void Button1_Click1(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string insertQuery = "insert INTO Students(Firstname,Secondname,Telephone,IDCity,Dateofbirth,ID) values(#firstName,#secondName,#telephone,#idCity,#dateOfbirth ,#id)";
SqlCommand com = new SqlCommand(insertQuery, conn); //
com.Parameters.AddWithValue("#firstName", firstname.Text);//adding
com.Parameters.AddWithValue("#secondName", secondname.Text);//adding
com.Parameters.AddWithValue("#telephone", telephone.Text);//adding
com.Parameters.AddWithValue("#idCity", idcity.Text);//adding
com.Parameters.AddWithValue("#dateOfbirth", dateofbirth.Text);//adding
com.Parameters.AddWithValue("#id", id.Text);//
com.ExecuteNonQuery();
Response.Write("Registration is successful");
conn.Close();
}

Related

How can I use transaction in this code?

I was trying to use this code without transaction but it gave me error, so I want to use it with transaction. How I can use it?
My code is:
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
private void btn_Update_Click(object sender, EventArgs e)
{
string query = "insert into users(Name, Password) values('ubaid', 'ali')";
cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
}
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
SqlTransaction trans;
private void btn_Update_Click(object sender, EventArgs e)
{
try
{
con.Open();
trans = con.BeginTransaction(); // Begins transaction
string query = "insert into users(Name,Password)values('ubaid','ali')";
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
trans.Commit();
}
catch (Exception ex) //error occurred
{
trans.Rollback(); // Rollback transaction on error
}
}
Try the above code. Hope it helps you.

exception thrown while connecting to database: connection property has not been initialized

I am trying basic database insert and this code is waht I am running in visual studio 2010:-
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True";
SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')");
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
where am I wrong?
You created a connection and opened it, but you did not associate it with the SqlCommand. You can do this a couple of ways, either in the constructor of the SqlCommand or through the Connection property of the SqlCommand.
Additionally, you should use parameterized queries to prevent SQL Injection attacks. I'd also recommend putting the SqlConnection in a using block to ensure it is closed and properly disposed of. Putting all of that together gives you something like this:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("insert into names values(#name)", conn);
// Alternatively, you could do cmd.Connection = conn if you didn't pass
// the connection object into the SqlCommand constructor
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.ExecuteNonQuery();
}
}
You did not assign the connection to the command object. try:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True";
SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')");
cmd.Connection = conn; // <- this is the missing line
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

Emp timeout time not saving in database

I am making emp time attendance register. I am using below code .. here insert query working fine and time-in successfully save in database timein field. Update query also execute successfully but databasae not updated...anyone please help for this...
private void checkin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source............");
conn.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "insert into timeatten (id,name,timein)values('" +comboBox1.Text+"','"+textBox1.Text+"','"+textBox2.Text+"' )";
comm.Connection = conn;
comm.ExecuteNonQuery();
MessageBox.Show("Successfully check in");
conn.close();
}
private void checkout_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source.............");
conn.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "update timeatten set timeout='" + textBox2.Text + "' where id='" + comboBox1.Text +"'";
MessageBox.Show("Successfully Checkout");
conn.close();
}
I think you're missing these two lines in checkout_Click:
comm.Connection = conn;
comm.ExecuteNonQuery();

Execute reader connection error

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MJ-PC;Initial Catalog=Test;Integrated Security=True ");
con.Open();
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
//SqlCommand cmd = con.CreateCommand();
SqlCommand cmd = new SqlCommand("select password from TestDemo where userName'" + txtusername .Text+ "'", con);
//cmd.Connection = con;
SqlDataReader da;
da = cmd.ExecuteReader();
if (!da.Read())
{
Response.Write("Wrong Details");
}
else
{
if(da[0].ToString()==txtusername.Text)
Response.Redirect("WebForm1.aspx");
else
Response.Write("Wrong Password");
}
}
where username **=**
forgot equality sign
Also, the conenction you open and the connection you use are different
The way I see it, you open a connection to the SQL server in Page_Load handler. But you don't close it.
If you try to open another one, or try to execute on a closed SqlConnection object, you might get an error.
A good way to do this is do something like this:
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
//do something here
}
catch (Exception)
{
/*Handle error*/
}
}
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection("Data Source=MJ-PC;Initial Catalog=Test;Integrated Security=True");
con.Open();
}
catch
{
//Handles exceptions here
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
try
{
//SqlCommand cmd = con.CreateCommand();
SqlCommand cmd = new SqlCommand("select password from TestDemo where userName='" + txtusername .Text+ "'", con);
//cmd.Connection = con;
SqlDataReader da;
da = cmd.ExecuteReader();
if (!da.Read())
{
Response.Write("Wrong Details");
}
else
{
if(da[0].ToString()==txtusername.Text)
Response.Redirect("WebForm1.aspx");
else
Response.Write("Wrong Password");
}
}
finally
{
con.Close();
}
}
If you code for login, then here a neat version code, Depend on your flagset you can redirect or display wrong password msg
bool flagset=false;
SqlDataReader dr;
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select password from TestDemo where userName=#uName";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#uName", txtusername.Text);
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows){
while (dr.Read())
{
if(dr[0].ToString()==txtusername.Text)
{ flagset=true; }
}
}dr.Close();
con.Close();
}
}return flagset;

fetching the label text from database in C#

private void button5_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='1'", conn);
conn.Open();
label1.Text = cmd.ExecuteReader().ToString();
conn.Close();
SqlConnection conn1 = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='2'", conn1);
conn1.Open();
label2.Text = cmd1.ExecuteReader().ToString();
conn1.Close();
SqlConnection conn2 = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd2 = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='3'", conn2);
conn2.Open();
label3.Text = cmd2.ExecuteReader().ToString();
conn2.Close();
}
I am developing a small project in C#... Using Visiual Studio 2010... I want to fetch the label texts from database in order to change the user interface language with a button...
I wrote this code but there is a problem in SQLDATAREADER
in label text parts it shows
System.Data.SqlClient.SqlDataReader
I cant fix, could you help me?
you can use ExecuteScalar()
label3.Text = (string) cmd2.ExecuteScalar();
if you want to use ExecuteReader you have to store the reader first, then call Read on it and fetch it values with reader.GetString(0);

Categories

Resources