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

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();
}

Related

Unable to insert values in sql server local db using c#

I'm unable to insert data into table. we are using local db. I'm not even getting any exception
string constr = ConfigurationManager.ConnectionStrings["server"].ConnectionString;
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("insert into Client_Name(Name) values('" + textBox1.Text + "')",con);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
Console.Write("Exception");
}
}
In app.config
<connectionStrings>
<add name="server" connectionString="Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Integrated
Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
I have tried all the possible way, and got the best solution considering your scenario.
During an hour observation got to know due database connection
persistence issue you were having that problem try below snippet would
work as expected.
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Connect Timeout=30;Integrated Security=True;";
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("Insert into [LocalTestTable] values (#name,#description)", _connection))
{
command.Parameters.AddWithValue("#name", "TestFlatName");
command.Parameters.AddWithValue("#description", "TestFlatDescription");
SqlDataReader sqlDataReader = command.ExecuteReader();
sqlDataReader.Close();
}
_connection.Close();
}
Hope that will resolve your problem without having anymore issue.

must declare the scalar variable #TextBox1 asp.net

this is the part of the code that i am sharing for the solution of my new application.
when i execute this code,it throws exception "Must declare the scalar variable #textBox1"
public partial class About : Page
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = "Data Source=.;Initial Catalog=carpro;Integrated Security=True";
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Insert into Driver_Registration(Driver_Name,Driver_DOB,Driver_Address,License_Number,National_Insurance_Number,"+
"Email_Address,UK_History,Contact,Occupation,License_Details,Taxi_License_Number,"+
"Deposit_Details,Weekly_Rent) Values (#TextBox1,#TextBox2,#TextBox3,#TextBox4,#TextBox5," +
"#TextBox6,#TextBox7,#TextBox8,#TextBox9,#TextBox10,#TextBox11,#TextBox12,#TextBox13)",con);
cmd.Parameters.AddWithValue("#Driver_Name",TextBox1.Text);
cmd.Parameters.AddWithValue("#Driver_DOB", TextBox2.Text);
cmd.Parameters.AddWithValue("#Driver_Address", TextBox3.Text);
cmd.Parameters.AddWithValue("#License_Number", TextBox4.Text);
cmd.Parameters.AddWithValue("#National_Insurance_Number", TextBox5.Text);
cmd.Parameters.AddWithValue("#Email_Address", TextBox6.Text);
cmd.Parameters.AddWithValue("#UK_History", TextBox7.Text);
cmd.Parameters.AddWithValue("#Contact", TextBox8.Text);
cmd.Parameters.AddWithValue("#Occupation", TextBox9.Text);
cmd.Parameters.AddWithValue("#License_Details", TextBox10.Text);
cmd.Parameters.AddWithValue("#Taxi_License_Number", TextBox11.Text);
cmd.Parameters.AddWithValue("#Deposit_Details", TextBox12.Text);
cmd.Parameters.AddWithValue("#Weekly_Rent", TextBox13.Text);
cmd.ExecuteNonQuery();
Label1.Text = "Registration Successfull";
con.Close();
}
}
The parameters you are using in your INSERT statement are not the same parameters you are creating in your cmd.Parameters.AddWithValue(..). Replace the INSERT parameters to the ones you actually created like #Driver_Name.
Also, you should move your
con.ConnectionString = "Data Source=.;Initial Catalog=carpro;Integrated Security=True";
con.Open();
down to your button. Essentially you are only opening your connection once, then closing it on button click. Currently, there is no way to re-open the connection without re-starting the application.
Or better yet segment it off into its own class/function.
Or even better, setup the connection string in the web.config and call it from there utilizing dependency injection.
in your query you specify the parameters:
(#TextBox1,#TextBox2,#TextBox3,#TextBox4,#TextBox5," +
"#TextBox6,#TextBox7,#TextBox8,#TextBox9,#TextBox10,#TextBox11,#TextBox12,#TextBox13)
you have 2 options
1 you can change your query to :
VALUES(#Driver_Name,......
2 you can change you AddWithValue to:
cmd.Parameters.AddWithValue("#TextBox1",TextBox1.Text);
...

Insert into database button code not working unsure how to fix it

I have tried to fix it but it wont take the three words i try to insert. it says error
"Format of the initialization string does not conform to specification
starting at index 0."
here is the button code
private void button5_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection("ConnectionOne");
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO test.lifestyle(animal_food,animal_hobbies,animal_sport) values('" + this.food_txt.Text + "','" + this.hobby_txt.Text + "','" + sport_txt.Text + "');");
cmd.ExecuteNonQuery();
con.Close();
}
The ConnectionOne is the name of the connection i have made with the data base
I strongly suspect you have a variable as ConnectionOne and this saves your string.
In such a case, you need to use it as;
SqlConnection con = new SqlConnection(ConnectionOne);
But more important, you should always use paramterized queries. This kind of string concateanations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection and SqlCommand instead of calling .Close() method manually.
private void button5_Click(object sender, RoutedEventArgs e)
{
using(var con = new SqlConnection(ConnectionOne))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"INSERT INTO test.lifestyle(animal_food,animal_hobbies,animal_sport)
values(#food, #hobbies, #sport)";
cmd.Parameters.AddWithValue("#food", this.food_txt.Text);
cmd.Parameters.AddWithValue("#hobbies", this.hobby_txt.Text);
cmd.Parameters.AddWithValue("#sport", sport_txt.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}

SQL query is not being executed in C#

I have a SQL query and I want to execute it in C# on a button click, but when I click the
button the database is not being affected:
private void button1_Click(object sender, EventArgs e) {
String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.CommandText = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
con.Close();
}
The code you want is this:
String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
String sql = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
cmd.ExecuteNonQuery();
}
Add cmd.ExecuteNonQuery after setting the command text.
You need to actually execute the query (try ExecuteNonQuery).
You're currently opening a connection, setting the statement to execute, then just closing the connection.

Deleting records from the created form in c#

I m working with c#, in this i want to delete record from the form for that i have the following code..
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
con.Open();
string sql = "DELETE FROM tblCompany WHERE (CoCode = 1)";
}
but i m not getting the answer...
You need to setup an OleDbCommand
The full code for your case,
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
string sql = "DELETE FROM tblCompany WHERE (CoCode = 1)";
con.Open();
OleDbCommand cmd = new OleDbCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
}
For more information of the whole implementation, read here
http://www.java2s.com/Code/CSharp/Database-ADO.net/DeletedatabaserecordsthroughOleDbCommandandverifytheresults.htm
You need to execute an OleCommand with your SQL and connection.

Categories

Resources