I Have a problem in connecting my database to c# in connection string section
this is my code but when i run it , i get an error about this :
"Format of the initialization string does not conform to specification
starting at index 84"
My Code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection Cn = new SqlConnection(#" Server=TheAddress ; Database=MyDataBase.mdf ; integrated security='True' #");
Cn.Open();
SqlCommand Cm = new SqlCommand("", Cn);
Cm.CommandText = "INSERT INTO Table1(ID_Food, Name_Food , TypeOfService_Food , Price_Food , Type_Food) VALUES (#ID_Food , #Name_Food , #TypeOfService_Food , #Price_Food , #Type_Food)";
Cm.Parameters.AddWithValue("#ID_Food", textBox1.Text);
Cm.Parameters.AddWithValue("#Name_Food", textBox2.Text);
Cm.Parameters.AddWithValue("#TypeOfService_Food", textBox3.Text);
Cm.Parameters.AddWithValue("#Price_Food", textBox4.Text);
Cm.Parameters.AddWithValue("#Type_Food", textBox5.Text);
Cm.ExecuteNonQuery();
Cn.Close();
}
I Cant Even Open My Connection (Error Happen in declaring SqlConnection)
I know its an Amature Question ... but its made me angry (i cant set it correctly)(with visual studio 2012 & sqlserver management studio 2012)
Looks like you have a "#" at the end you should remove from the connection string. You also might consider using the using statements when creating the SqlConnection and SqlCommand objects so they are properly disposed.
using (var Cn = new SqlConnection(#"Server=TheAddress;Database=MyDataBase.mdf;integrated security=True"))
{
Cn.Open();
using (var Cm = new SqlCommand("", Cn))
{
Cm.CommandText = "INSERT INTO Table1(ID_Food, Name_Food , TypeOfService_Food , Price_Food , Type_Food) VALUES (#ID_Food , #Name_Food , #TypeOfService_Food , #Price_Food , #Type_Food)";
Cm.Parameters.AddWithValue("#ID_Food", textBox1.Text);
Cm.Parameters.AddWithValue("#Name_Food", textBox2.Text);
Cm.Parameters.AddWithValue("#TypeOfService_Food", textBox3.Text);
Cm.Parameters.AddWithValue("#Price_Food", textBox4.Text);
Cm.Parameters.AddWithValue("#Type_Food", textBox5.Text);
Cm.ExecuteNonQuery();
Cn.Close();
}
}
you need to provide valid connection string .
Try This :
SqlConnection Cn = new SqlConnection(#"Data Source=TheAddress;Initial Catalog=MyDataBase.mdf;Integrated Security=True");
EDIT : from comments : as you are getting runtime excpetion please check wether you are able to communicate with the server or not.
Check this here
Related
I'm trying to modify an specific register on Access by C# but when I run the code, It doesn't modify anything, I have tried the same structure on adding resgisters or deleting and it works well, Help please
using OleDB
dataGridView1.Rows.Clear();
string sql = "UPDATE Medicos SET Id_clinica=#Id_clinica, Id_especialidad=#Id_especialidad, Nombre=#Nombre, Apellidos=#Apellidos WHERE Id_medico=#Id_medico";
OleDbConnection con = new OleDbConnection(cs);
con.Open();
OleDbCommand cmd = new OleDbCommand(sql, con);
cmd.Parameters.AddWithValue("#Id_medico", textBox1.Text);
cmd.Parameters.AddWithValue("#Id_clinica", textBox2.Text);
cmd.Parameters.AddWithValue("#Id_especialidad", textBox3.Text);
cmd.Parameters.AddWithValue("#Nombre", textBox4.Text);
cmd.Parameters.AddWithValue("#Apellidos", textBox5.Text);
cmd.ExecuteNonQuery();
con.Close();
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);
...
What is wrong with my code? When Im setting up the connection between sql server management studio and c#, it gives me this error " ExecuteNonQuery: Connection property has not been initialized."
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString= "Database= hotel; server= Sherissa\SQLEXPRESS";
con.Open();
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId,#GuestName,#RoomType,#RoomNo,#ReservationDate,#CheckInDate,#CheckOutDate,#NoOfDays,#NoOfAdults,#NoOfChildren)");
cmd.Parameters.AddWithValue("#TransactionId",textBox1.Text);
cmd.Parameters.AddWithValue("#GuestName", textBox2.Text);
cmd.Parameters.AddWithValue("#RoomType", textBox3.Text);
cmd.Parameters.AddWithValue("#RoomNo", textBox4.Text);
cmd.Parameters.AddWithValue("#ReservationDate", textBox5.Text);
cmd.Parameters.AddWithValue("#CheckInDate", textBox6.Text);
cmd.Parameters.AddWithValue("#CheckOutDate", textBox7.Text);
cmd.Parameters.AddWithValue("#NoOfDays", textBox8.Text);
cmd.Parameters.AddWithValue("#NoOfAdults", textBox9.Text);
cmd.Parameters.AddWithValue("#NoOfChildren", textBox10.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("DATA ADDED SUCCESSFULLY!!");
}
I see several errors here.
The first error is the substance of your question. To solve that issue, you need to associate your command with a particular connection. Remember, you might be connected to several different databases at the same time. A command needs to know which connection to use.
The next error is that your Sql syntax is wrong. You are missing the required VALUES keyword.
Another problem is that you don't close the connection correctly. If an exception is thrown, the code will never make it to the con.Close(); line. If this happens often enough you will lock yourself out of your database.
Finally, a nitpick. I'm not a fan of the .AddWithValue() method, because it forces .Net to try to guess the sql datatype you're using. Sometimes it guesses wrong, and when it does the performance implications can be severe, because it can break index use on the database.
Here is code that solves all four issues:
private void button1_Click(object sender, EventArgs e)
{
using (var con = new SqlConnection("Database= hotel; server= roger\SQLEXPRESS"))
using (var cmd = new SqlCommand("insert into CheckIn VALUES (#TransactionId,#GuestName,#RoomType,#RoomNo,#ReservationDate,#CheckInDate,#CheckOutDate,#NoOfDays,#NoOfAdults,#NoOfChildren)", con))
{
cmd.Parameters.Add("#TransactionId", SqlDbType.Int).Value = int.Parse(textBox1.Text);
cmd.Parameters.Add("#GuestName", SqlDbType.NVarChar, 50).Value = textBox2.Text;
cmd.Parameters.Add("#RoomType", SqlDbType.NVarChar, 10).Value = textBox3.Text;
cmd.Parameters.Add("#RoomNo", SqlDbType.NChar, 4).Value = textBox4.Text;
cmd.Parameters.Add("#ReservationDate", SqlDbType.DateTime).Value = datetime.Parse(textBox5.Text);
cmd.Parameters.Add("#CheckInDate", SqlDbType.DateTime).Value = datetime.Parse(textBox6.Text);
cmd.Parameters.Add("#CheckOutDate", SqlDbType.DateTime).Value = datetime.Parse(textBox7.Text);
cmd.Parameters.Add("#NoOfDays", SqlDbType.Int).Value = int.Parse(textBox8.Text);
cmd.Parameters.Add("#NoOfAdults", SqlDbType.Int).Value = int.Parse(textBox9.Text);
cmd.Parameters.Add("#NoOfChildren", SqlDbType.Int).Value = int.Parse(textBox10.Text);
con.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("DATA ADDED SUCCESSFULLY!!");
}
Of course I had to guess at the datatypes to use, and in my own code I would also devote a little more effort to validating the inputs before trying to parse them.
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId, #GuestName, #RoomType, #RoomNo, #ReservationDate, #CheckInDate, #CheckOutDate, #NoOfDays, #NoOfAdults, #NoOfChildren)");`
This line should be typed as,
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId, #GuestName, #RoomType, #RoomNo, #ReservationDate, #CheckInDate, #CheckOutDate, #NoOfDays, #NoOfAdults, #NoOfChildren)", con );
You need to assign the connection to your command:
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId,#GuestName,#RoomType,#RoomNo,#ReservationDate,#CheckInDate,#CheckOutDate,#NoOfDays,#NoOfAdults,#NoOfChildren)", con);
I've created a database and a table with 2 fields Id and Name.
Now I want to insert values on clicking a button the sammple code is given. it's not working.
using (SqlConnection connection = new SqlConnection(strConnection))
{
SqlCommand command =new SqlCommand("insert into Test (Id,Name) values(5,kk);",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
String values should be in quotes. This has not much to do with C#, more with T-SQL
Try this, and notice the kk;
SqlCommand command =
new SqlCommand("insert into Test (Id,Name) values(5,'kk');",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Also I am assuming here that Id is not an auto-increment field. If it is, then you should not fill it.
As a side-node you should look at parameterized queries to prevent SQL injection.
In this instance, you need single quotes ' around the kk
insert into Test (Id,Name) values(5,'kk')
In general, you should use parameterised queries
try this:
SqlConnection conn = new SqlConnection();
SqlTransaction trans = conn.BeginTransaction();
try
{
using (SqlCommand cmd = new SqlCommand("insert into Test (Id,Name) values(#iD, #Name)", conn, trans))
{
cmd.CommandType = CommandType.Text;
cmd.AddParameter(SqlDbType.UniqueIdentifier, ParameterDirection.Input, "#iD", ID);
cmd.AddParameter(SqlDbType.VarChar, ParameterDirection.Input, "#Name", Name);
cmd.ExecuteNonQuery();
}
conn.CommitTransaction(trans);
}
catch (Exception ex)
{
conn.RollbackTransaction(trans);
throw ex;
}
Try this:
SqlConnection con = new SqlConnection('connection string here');
string command = "INSERT INTO Test(Id, Name) VALUES(5, 'kk')";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
String values should be between ' '
Verify your connection string
//add your connection string between ""
string connectionString = "";
using (var conn = new SqlConnection(connectionString))
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO pdf (Id, Name) VALUES (5, 'kk')";
conn.Open();
conn.ExecuteNonQuery();
conn.Close();
}
It looks like you have multiple problems with your current code.
You need to enclose string values in single quotes, as pointed out in other answers.
You need to enable remote connection to your SQL server.
Check the following link if you are using SQL server 2008.
How to enable remote connections in SQL Server 2008?
and for SQL Server 2005 see:
How to configure SQL Server 2005 to allow remote connections
I'm trying to insert a textbox value to a database table called site_list.
The site_list table contains two columns id and site_name, id set to auto increment
This is the code I'm trying and when it execute there is no error, but the data is not showing up in the table
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|scraper_db.mdf;";
SqlCommand addSite = new SqlCommand("INSERT INTO site_list (site_name) "
+ " VALUES (#site_name)", conn);
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = textBox1.Text;
conn.Open();
addSite.ExecuteNonQuery();
conn.Close();
Any help would be appreciated.
Regards
Edit:
This code started to work
string connstring = "Data Source=.\\SQLExpress;"+
"Integrated Security=true;"+
"User Instance=true;"+
"AttachDBFilename=|DataDirectory|scraper_db.mdf;"+
"Initial Catalog=scraper_db";
using (SqlConnection connection = new SqlConnection(connstring))
{
connection.Open();
SqlCommand addSite = new SqlCommand("INSERT INTO site_list (site_name)"+
"VALUES (#site_name)", connection);
addSite.Parameters.AddWithValue("#site_name", textBox1.Text);
addSite.ExecuteNonQuery();
connection.Close();
}
as people suggests, try creating the database on the server (it will be even easier to handle using Sql Management Studio).
Once that's done, try the following (just tested and it works):
using (SqlConnection conn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)"))
{
SqlCommand addSite = new SqlCommand(#"INSERT INTO site_list (site_name) VALUES (#site_name)", conn);
addSite.Parameters.AddWithValue("#site_name", "mywebsitename");
addSite.Connection.Open();
addSite.ExecuteNonQuery();
addSite.Connection.Close();
}
try
{
using (SqlConnection conn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)\SQLEXPRESS;database=Inventory;Data Source=localhost\SQLEXPRESS;"))
{
SqlCommand addSite = new SqlCommand(#"INSERT INTO Creation (Name,Product,Quantity,Category) VALUES (#Name,#Product,#Quantity,#Category)", conn);
addSite.Parameters.AddWithValue("#Name", textBox1.Text);
addSite.Parameters.AddWithValue("#Product", textBox2.Text);
addSite.Parameters.AddWithValue("#Quantity", textBox3.Text.ToString());
addSite.Parameters.AddWithValue("#Category", textBox4.Text);
thisConnection.Open();
addSite.ExecuteNonQuery();
}
}
catch
{
thisConnection.Close();
}
try this out :
string sql = String.Format("INSERT INTO site_list (site_name) VALUES('{0}')", myTextBox.Text);
using(SqlConnection connection = new SqlConnection(myConnectionString))
{
connection.open();
using(SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.ExecuteNonQuery();
}
}
Good luck
Try storing your textbox value in a variable. As in:
#stringname = textbox1.text
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = #stringname;
(IMPORTANT! the # in #stringname is not necessary, but protects you against hackers!)
This code has worked wonders for me.
My apologies. The answer I gave previously will not work because the variable name used in the insert command (in your case #site_name) must match the variables used in your sqlcommand. As in:
#site_name = textbox1.text
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = textBox1.Text;
Sorry for the confusion I might have caused.