I'm trying to connect to database and I get the following error:
Illegal characters in path.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection Con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\targil3.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlDataAdapter adapt = new SqlDataAdapter();
adapt.InsertCommand = new SqlCommand(" INSERT INTO tblEmployee VALUES (#employeeNumber, #employeePrivateName, #employeeFamilyName ,#city, #street, #houseNo, #phoneNumber, #birthDate, #startWorkingDate)", Con);
adapt.InsertCommand.Parameters.Add("#employeeNumber", SqlDbType.Char).Value = textBox1.Text;
adapt.InsertCommand.Parameters.Add("#employeePrivateName", SqlDbType.VarChar).Value = textBox2.Text;
adapt.InsertCommand.Parameters.Add("#employeeFamilyName", SqlDbType.VarChar).Value = textBox3.Text;
adapt.InsertCommand.Parameters.Add("#city", SqlDbType.VarChar).Value = textBox4.Text;
adapt.InsertCommand.Parameters.Add("#street", SqlDbType.VarChar).Value = textBox5.Text;
adapt.InsertCommand.Parameters.Add("#houseNo", SqlDbType.Int).Value = textBox6.Text;
adapt.InsertCommand.Parameters.Add("#phoneNumber", SqlDbType.Char).Value = textBox7.Text;
adapt.InsertCommand.Parameters.Add("#birthDate", SqlDbType.DateTime).Value = Convert.ToDateTime(textBox8.Text);
adapt.InsertCommand.Parameters.Add("#startWorkingDate", SqlDbType.DateTime).Value = Convert.ToDateTime(textBox8.Text);
Con.Open();
adapt.InsertCommand.ExecuteNonQuery();
Con.Close();
}
How to do I connect to the database so the I can insert into it?
You'll need to escape \targil3.mdf
Use \\ or put an # before the assignment of the string, for instance.
SqlConnection Con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\targil3.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
This is because you have got characters in your connection string which need to be escaped. To overcome this issue you have got couple of options.
Either to explicitly escape those characters by using
\\
OR
use the # sign before assignment.
PS: Though i would recommend you to specify your connection string in app.config and read it like this
string conString = System.Configuration.ConfigurationManager.ConnectionStrings["yourConnectionString"].ToString();
and you should consider the user of
using (SqlConnection sqlConn = new SqlConnection(conString ))
{
try
{
//your sql statements here
}
catch (InvalidOperationException)
{
}
catch (SqlException)
{
}
catch (ArgumentException)
{
}
}
You won't face any errors specified above.
Related
I have tried this code in C#, and it's not working - I can't get an input id, every time I run it, the value of id is 0.
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco");
int id;
con.Open();
string sql = "select * from Staff_Management where Emp_Name = '"+sName+"'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader read = cmd.ExecuteReader();
if (read.Read())
{
id = read.GetInt32(0);
TM_AC_SelectId.Text = id.ToString();
}
else
{
MessageBox.Show("Error 009 ");
}
con.Close();
You should try to follow the accepted best practices for ADO.NET programming:
use parameters for your query - always - no exceptions
use the using(...) { .... } construct to ensure proper and quick disposal of your resources
select really only those columns that you need - don't just use SELECT * out of lazyness - specify your columns that you really need!
Change your code to this:
// define connection string (typically loaded from config) and query as strings
string connString = "Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco";
string query = "SELECT id FROM dbo.Staff_Management WHERE Emp_Name = #EmpName;";
// define SQL connection and command in "using" blocks
using (SqlConnection con = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// set the parameter value
cmd.Parameter.Add("#EmpName", SqlDbType.VarChar, 100).Value = sName;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
con.Close();
int id;
if(result != null)
{
if (int.TryParse(result.ToString(), out id)
{
// do whatever when the "id" is properly found
}
}
}
This is the code I'm working with right now, I don't get any errors so I can't pinpoint where it's not working:
private void btnAdd_Click(object sender, EventArgs e)
{
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
string query =
"INSERT INTO Products (Barcodes, Name, EDate, Quantity, Price) VALUES (#barcodeValue, #nameValue, #dateValue, #quantityValue, #priceValue) ;";
SqlConnection conDataBase = new SqlConnection(constring);
conDataBase.Open();
using (var cmd = new SqlCommand(query, conDataBase))
{
cmd.Parameters.AddWithValue("#barcodeValue", tbxBar.Text);
cmd.Parameters.AddWithValue("#nameValue", tbxName.Text);
cmd.Parameters.AddWithValue("#dateValue", dateDate.Value.Date);
cmd.Parameters.AddWithValue("#quantityeValue", tbxQua.Text);
cmd.Parameters.AddWithValue("#priceValue", tbxPrice.Text);
}
conDataBase.Close();
}
The code might just be wrongly build or I could be missing some part I'm not sure.
I figured out what was not working, was the connection string. So opening a new question for that.
What i had to do is to open the connection and then execute the command
You're not actually running the command. You need to call ExecuteNonQuery or ExecuteScalar:
using (var cmd = new SqlCommand(query, conDataBase))
{
// set parameters...
cmd.ExecuteNonQuery();
}
I am trying to build a registration web form which saves user data into an SQL table. This is what I have so far:
public static SqlConnection GetConnection()
{
String connection;
connection = #"example/file/path";
return new SqlConnection(connection);
}
protected void submitButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = GetConnection();
try
{
myConnection.Open();
String myQuery = "INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password]) values ('"
+fNameBox.Text+ "' ,'"+ lNameBox.Text+"' ,'"+emailBox.Text+"' ,'"
+ dobBox.Text+"', '"+userNameBox.Text+"' ,'"+passwordBox.Text+"';)";
SqlCommand myCommand = new SqlCommand(myQuery, GetConnection());
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
myConnection.Close();
}
}
The error occurs in my GetConnection() method where I return the connection. The error I get is:
An exception of type 'System.ArgumentException' occurred in
System.Data.dll but was not handled in user code
Additional information: Format of the initialization string does not conform to specification starting at index 0.
I do not know how to get past this problem but any help is very appreciated.
Your problem lies in
String connection;
connection = #"example/file/path";
return new SqlConnection(connection);
your connectionString variable (connection in your case) is not set properly, there are multiple ways to do that just to list 2 of the most common ones.
Standard Connection with username and password:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();
Trusted Connection:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"Integrated Security=SSPI;";
conn.Open();
You might want to look at this question for example:
How to set SQL Server connection string?
Pijemcolu's answer is correct, but I think several things can be added to enhance your code:
1) use proper names for variables. E.g.: connection string is different from actual connection
public static SqlConnection GetConnection()
{
// if Windows Authentication is used, just get rid of user id and password and use Trusted_Connection=True; OR Integrated Security=SSPI; OR Integrated Security=true;
String connStr = "Data Source=ServerName;Initial Catalog=DataBaseName;User id=UserName;Password=Secret;";
return new SqlConnection(connStr);
}
2) Try to dispose disposable objects (i.e. implement IDisposable) should be properly disposed.
Also, commands should not constructed with string concatenation, but using parameters. This is particularly important when providing direct user input into the query, since malicious users might try to perform queries to compromise the data (read more about SQL injection here).
The connection can be closed only within finally block, since everything there is executed no matter what (exception raised or not in the catch block).
protected void submitButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = null;
try
{
using (myConnection = GetConnection())
{
myConnection.Open();
String myQuery = #"
INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password])
values (#firstName, #lastName, #eMail, #dob, #userName, #password)";
using (SqlCommand myCommand = new SqlCommand(myQuery, GetConnection())
{
myCommand.Parameters.AddWithValue("#firstName", fNameBox.Text);
myCommand.Parameters.AddWithValue("#lastName", lNameBox.Text);
myCommand.Parameters.AddWithValue("#eMail", emailBox.Text);
myCommand.Parameters.AddWithValue("#dob", dobBox.Text);
myCommand.Parameters.AddWithValue("#userName", userNameBox.Text);
myCommand.Parameters.AddWithValue("#password", passwordBox.Text);
myCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (myConnection != null)
myConnection.Close();
}
}
3) Password storage
It looks like your storing password typed by the user. It is strongly recommended to store a representation of the password (some sort of hash that it is easy to compute from a string, but the string is almost impossible to be retrieved from the hash). More details can be found here.
I need to add a text box value to SQL Server database table. Below is my code:
private void button1_Click(object sender, EventArgs e)
{
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(str);
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
con.Close();
}
But, data should not add in table... please help me...
thanks for ur help...
Try debugging your query first if it works i think your connection with your db isnt working.
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
is there supposed to be this '.' after data source Data Source=.\\SQLEXPRESS
try this and tell me what is the message information content
private void button1_Click(object sender, EventArgs e)
{
string str = "Server=.\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;";
using( SqlConnection con = new SqlConnection(str)){
try{
con.Open();
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
}
catch{
MessageBox.Show("connection is failed!!");
}
}
}
try this
SqlConnection con = new SqlConnection(#"Data Source=SL-20\SQLEXPRESS;Initial Catalog=TestDB;User ID=sa;Password=sl123;");
string query = " insert into name(name)values('" + TextboxTest.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
Could somebody tell me why this isn't adding the values to the database. The form runs fine and doesn't return any errors.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
command.Parameters.AddWithValue("#userName", textBox1.Text);
command.Parameters.AddWithValue("#passWord", textBox2.Text);
command.CommandText = "INSERT INTO Setup (userName, password) VALUES(#userName, #passWord)";
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
// handle exception
}
finally
{
connection.Close();
}
}
FYI: I'm a "newbie" My database is called Setup. I've manually added a table called myTable with 2 columns of userName and another one called password both set at nchar(50)
You need to specify the Table, not the database (which gets used in the connection string). Added the schema prefix to the table name:
command.CommandText = "INSERT INTO dbo.myTable (userName, password) VALUES (#userName, #passWord)";
And add:
command.Connection = connection;
to associate your Command object with the connection object.
Your code should look something like this:
Set the connection object.
Specify the table name as #LarsTech has mentioned.
It is a best practice to use two part notation when specifying table names like [Schema name].[Table Name]. So, you have to specify your table name like dbo.MyTable
Code snippet:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;");
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO dbo.MyTable (userName, password) VALUES (#userName, #passWord)";
command.Parameters.AddWithValue("#userName", textBox1.Text);
command.Parameters.AddWithValue("#passWord", textBox2.Text);
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
catch (Exception ex)
{
//handle exception
}
finally
{
connection.Close();
}
}
The form runs fine and doesn't return any errors.
That's probably because you're swallowing them. Get rid of (or log) your catch (Exception ex).
In general, the .NET BCL is well-designed - if a method isn't going to work, you will get an exception.
[Now] I have the error 'ExecuteNonQuery: Connection property has not been initialized.'
Right. You need to pass the SqlConnection to the SqlCommand:
SqlCommand command = new SqlCommand();
command.Connection = connection;