My database layout looks like this:
-App_Data
-Database.mdf
-Database_log.ldf
and this is my code:
string strConn = "Data Source=.\\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True;";
SqlConnection myConn = new SqlConnection(strConn);
myConn.Open();
String strSQL = "INSERT INTO dbo.member (Id, Password, Name, Jobtitle,level,phone) VALUES ('a01', '123', 'bobo', 'Tester','1','010919')";
SqlCommand myCommand = new SqlCommand(strSQL, myConn);
myConn.Close();
When I test in browser, however, it sends an error message and stops in this code "myConn.Open();"can't find server
Why is this happening?
change
string strConn = "Data Source=.\\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True;";
to
string strConn = #"Data Source=.\SQLExpress;Initial Catalog=Database;Integrated Security=True";
Attach a database file, located in the data directory, on connect to a
local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|dbfilename.mdf;Database=dbname;
Trusted_Connection=Yes;
so your connection string should be similar to below, replace database name corectly
string strConn =#"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database.mdf;Database=dbname; Trusted_Connection=Yes;";
using (SqlConnection myConn = new SqlConnection(strConn))
{
string strSQL = "INSERT INTO dbo.member (Id, Password, Name, Jobtitle,level,phone) VALUES ('a01', '123', 'bobo', 'Tester','1','010919')";
myConn.Open();
using(SqlCommand myCommand = new SqlCommand(strSQL, myConn))
{
myCommand.ExecuteNonQuery(); // you haven't execute the insert
}
}
Related
I am trying to make a portable connection string with a service-based database.
If I use
C:\Users\X\Desktop\C# Projects\Windows Form Applications\PortableConnectionString\PortableConnectionString\BazaDate.mdf
and not |DataDirectory|BazaDate.mdf, it works.
What can I do to make it portable?
SqlConnection conn= new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BazaDate.mdf;Integrated Security=True;");
conn.Open();
Environment.GetCommandLineArgs()[0] is the full path of your executable, thus:
string appPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
string connStr = $#"Data Source=(LocalDB)\v11.0;AttachDbFilename={appPath}\BazaDate.mdf;Integrated Security=True;";
var conn = new SqlConnection(connStr);
conn.Open();
I have a hard time figuring out what is wrong about my code. The purpose is to take data from a registering form in ASP to my user data columns in my SQL database.
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin
values(#UserName,#Password)";
SqlConnection cnn = new SqlConnection(cmd);
SqlCommand cmd2 = new SqlCommand(cmd, cnn);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();
You're using the connection string in the connection variable but the variable you're passing to SqlCommand is cnn which doesn't have a valid connection string associated with it.
I've cleaned up your code and made use of using block to ensure the correct manner of disposing the object. Please see below:
string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
string query = "insert into UserLogin values(#UserName, #Password)";
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd.Parameters.AddWithValue("#Password", PasswordBox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
You have two SqlConnection variable and assigning wrong one in the SqlCommand. The working code will be:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin values(#UserName, #Password)";
SqlCommand cmd2 = new SqlCommand(cmd, connection);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();
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.
I am a newbie to c#. I am trying to insert the values from the text box into the table in my database.
Table Name : address
Fields : name(varchar(50)),
age(int),
city(nchar(10))
When i try to retrieve the values from the database it is working perfectly.
Here is my code. Please help me rectify it.
string s = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
SqlConnection a = new SqlConnection(s);
a.Open();
SqlCommand comm = new SqlCommand("INSERT INTO [address](name,age,city) VALUES(#na,#ag,#ci)");
string na = textBox1.Text;
int ag = int.Parse(textBox2.Text);
string ci = textBox3.Text;
comm.Parameters.Add("#na", System.Data.SqlDbType.VarChar,50).Value = na;
comm.Parameters.Add("#ag", System.Data.SqlDbType.Int).Value = ag;
comm.Parameters.Add("#ci", System.Data.SqlDbType.NChar,10).Value = ci;
comm.Connection = a;
comm.ExecuteNonQuery();
MessageBox.Show("okay");
a.Close();
The values are not reflected in the database.
try with this code :
string connectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand insertCommand = connection.CreateCommand())
{
insertCommand.CommandText = "INSERT INTO address(name,age,city) VALUES (#na,#ag,#ci)";
insertCommand.Parameters.Add("#na", na);
insertCommand.Parameters.Add("#ag", ag);
insertCommand.Parameters.Add("#ci", ci);
insertCommand.Connection.Open();
insertCommand.ExecuteNonQuery();
}
}
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.