Failed to attach an auto-named database - c#

so I have a C# software which will save data to my database but every time I run my program and try to save data I get this message, please any help?
try
{
SqlConnection cnn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\Users\Hp\Documents\Visual Studio 2010\Projects\Bank_System\Bank_System\Bank_System.sdf;
Integrated Security=True;User Instance=True");
cnn.Open();
SqlCommand cmd1 =
new SqlCommand("insert into user values('" +
textBox6.Text + "','" + textBox1.Text + "','" + textBox4.Text + "'," +
textBox3.Text + ",'" + textBox2.Text + "','" + textBox5.Text + "')",
cnn);
SqlDataReader dr1 = cmd1.ExecuteReader();
dr1.Close();
MessageBox.Show(" Record inserted ", " information inserted");
cnn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}

Copy your database Bank_System.sdf in \bin\debug\ folder and change your connection string like this :
SqlConnection cnn = new SqlConnection("Data Source=" +#".\SQLEXPRESS;
AttachDbFilename=Bank_System.sdf;
Integrated Security=True;User Instance=True");
It should be worked, if an error occurs, try to execute your app from yourapp.exe located in \bin\debug\ folder

You are working with an SDF file. This file is for SQL Server Compact not for SQL Server Express (or full).
In this case the connection string should be simply:
#"Data Source=<fullpath_and file_to_your_sdf_file>;Persist Security Info=False;"
Notice that in C# you need to add the verbatim character in front of strings that contains special characters like the backslash
Working with Sql Server Compact requires to install the libraries required from the Microsoft Downloads and to use the proper classes. So, remove the SqlConnection and the SqlCommand classes and use the SqlCeConnection and SqlCeCommand (and so on for the other data client classes used in you app).
Of course the SqlCeConnection class can understand this different connection string syntax and allow to work with the SDF file
Said that, please revise your code that builds the sql command. Using string concatenation like your code does is a secure recipe for errors. From parsing errors (quotes inside your strings will break the syntax) to more serious error like Sql Injections
This could be an approach using a parameterized query....
try
{
string cmdText = "insert into user values(#p1, #p2, #p3,#p4,#p5,#p6)";
using(SqlCeConnection cnn = new SqlCeConnection(#"Data Source=C:\Users\Hp\Documents\Visual Studio 2010\Projects\Bank_System\Bank_System\Bank_System.sdf;Integrated Security=True"))
using(SqlCeCommand cmd1 = new SqlCeCommand(cmdText, cnn))
{
cnn.Open();
cmd.Parameters.AddWithValue("#p1", textBox6.Text);
cmd.Parameters.AddWithValue("#p2", textBox1.Text);
cmd.Parameters.AddWithValue("#p3", textBox4.Text);
cmd.Parameters.AddWithValue("#p4", textBox3.Text);
cmd.Parameters.AddWithValue("#p5", textBox2.Text);
cmd.Parameters.AddWithValue("#p6", textBox5.Text);
cmd1.ExecuteNonQuery();
MessageBox.Show(" Record inserted ", " information inserted");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}

Related

How to save a string in SQL Server as SqlDateType by using Visual Studio 2013?

How to save a string in SQL Server as SqlDateType by using Visual Studio 2013? My string which I want to save is 1996-25-04. I am working with C#.
I have tried this as far
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=sa;Password=pass");
con.Open();
string sql = " insert into Staff_Management values( '" + TM_Add_BirthDate.Value.ToString() + "' ";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved successfully");
You should NEVER EVER concatenate together your SQL statements like this! This opens all doors to SQL injection attacks - and causes trouble with string and date values.
Try this code instead - using a parametrized query:
// define the query - and I'd recommend to always define the name of the columns you're inserting into
string query = "INSERT INTO dbo.Staff_Management(name-of-column-here) VALUES (#Birthdate);";
// define connection and command
// also: do **NOT** use the `sa` user for your production code!
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=sa;Password=pass"))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// add the parameter - and use the proper datatype - don't convert all dates to strings all the time!
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = TM_Add_Birthdate.Value;
// open connection, execute INSERT query, close connection - done
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved successfully");
}

Insert command works without errors in C# but data is not inserted to the MS SQL Server

I am trying to insert data into Microsoft SQL Server DB using C# and the insert command works well and I get no errors or exceptions. But when I check my database in SQL Server there is no effect on the table and the records are not inserted into the table. This is the code that I try:
try
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.Connection = con1;
cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','#" + update.Message.Chat.Username + "','" + req1.Status + "')";
con1.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
continue;
}
I've seen similar questions here and here, but the answers did not fix my problem.
Also when I insert data to the DB manually and run select command like mentioned below, I get the correct answer but for the insert command I do not.
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con2.Open();
SqlDataAdapter da1 = new SqlDataAdapter("select * from Users where ChatID='" + update.Message.Chat.Id.ToString() + "'", con2);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
con1.Close();
Please help me fix this issue.
By the way I know that this kind of insertion is not safe and I'l like to let you know that this is just a demo and I will make it secure against sql injection.
You are not executing your command anywhere.
You need:
cm1.ExecuteNonQuery();
In your code, you are creating a SqlCommand object, then you associate a SqlConnection to it, but in no where you are actually executing the command. Your code should look like:
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.Connection = con1;
cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','#" + update.Message.Chat.Username + "','" + req1.Status + "'";
cm1.ExecuteNonQuery();
con1.Close();
Apart from SQL Injection vulnerability, you should consider enclosing your SqlCommand and SqlConnection object in using statement, that will ensure proper disposal of un-managed resources.

Data insertion in sql through C#

I have successfully created connection of database but now I'm having problem in insertion of data. Here is my code:
String Connection = null;
SqlConnection con;
SqlCommand cmd;
String sql = null;
Connection="Data Source=DELL\\SQLEXPRESS; initial Catalog= BSSE;Integrated Security=True";
con = new SqlConnection(Connection);
sql = "INSERT INTO Records (Roll_No,Name,Marks) VALUES (" + textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + ");";
try
{
con.Open();
cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
MessageBox.Show ("Success of data insertion ");
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
First, your SQL statement is incorrect. You are missing single quote between values field. Later, you build SQL statement by using string concatenation and this is dangerous because can be exposed to SQL Injection. Use Parameterized Query instead.
try
{
con.Open();
cmd = new SqlCommand("INSERT INTO Records (Roll_No,Name,Marks) VALUES (#rollNo, #Name, #Marks)", con);
cmd.Parameters.AddWithValue("#rollNo", textBox1.Text);
cmd.Parameters.AddWithValue("#Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Marks", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show ("Success of data insertion ");
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Check your connection string. I usually write it as:
string Connection = #"Data Source=DELL\SQLEXPRESS;Initial Catalog = BSSE; Integrated Security = true";
If the roll number is supposed to be an integer, you need to parse
it.
int.Parse(textBox1.Text)
I suggest to use store procedures instead of sending blocks of SQL code from the c# Application, here is a reference to the SQL Store Procedures: https://msdn.microsoft.com/en-us/library/ms190782.aspx. You can reduce the possibility of SQL injection by adding parameters to your query instead of plain text, also you need to validate the input. You can create calls with parameters too. There are many ways to call a SQL database query from C#, Here is more information about Store Procedures that can give you a clue: http://csharp-station.com/Tutorial/AdoDotNet/Lesson07

How to save data to a database when it's attached as service-based database?

I attached the service-based database to my windows application and I used the following code to save the data, it is working correctly, but when I close the application and open again the data which I saved was cleared automatically.
How to save the data permanently...
string c = Application.StartupPath + "\\Stock.mdf";
SqlConnection con = new SqlConnection(#"AttachDbFilename='"+c+"';Integrated Security=True;Connect Timeout=30;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("Insert into Codedetails values('TF','" + txt_productcode.Text + "','" + txt_productname.Text + "','" + txt_brandcode.Text + "','" + txt_brandname.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
first, it is better to use init catalog instead attached file (common practice)
secondly use using to dispose your ressources
thirdly, it is better to do your sql query in a stored procedure which take parameters (sql in database and C# in vs2010 ;-)
string c = Application.StartupPath + "\\Stock.mdf";
string connectionString = #"AttachDbFilename='"+c+"';Integrated Security=True;Connect Timeout=30;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(Insert into Codedetails values('TF','#productcode','#productname','#brandcode','#brandname'), con))
{
command.Parameters.Add(new SqlParameter("productcode", txt_productcode.Text));
command.Parameters.Add(new SqlParameter("productname", txt_productcode.Text));
command.Parameters.Add(new SqlParameter("brandcode", txt_brandcode.Text));
command.Parameters.Add(new SqlParameter("brandname", txt_brandname.Text));
command.ExecuteNonQuery();
}
}

display information from sql db to asp.net webpage

I think what I need is simple but I can't achieve it through asp.net because I am a total beginner.
What I need is to display a field from sql db table to my webpage like this example:
Account Information
Your Name is: <Retrieve it from db>
Your Email is: <Retrieve it from db>
How should I do that ?
I already have table members.
I need to do this with c# , I am using Visual Studio Web Express 2010
First step is add the SQL Client namespace:
using System.Data.SqlClient;
DB Connection
Then we create a SqlConnection and specifying the connection string.
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
This is the last part of getting connected and is simply executed by the following (remember to make sure your connection has a connection string first):
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand
An SqlCommand needs at least two things to operate. A command string, and a connection. There are two ways to specify the connection, both are illustrated below:
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
// - or -
myCommand.Connection = myConnection;
The connection string can also be specified both ways using the SqlCommand.CommandText property. Now lets look at our first SqlCommand. To keep it simple it will be a simple INSERT command.
SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)", myConnection);
// - or -
myCommand.CommandText = "INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)";
SqlDataReader
Not only do you need a data reader but you need a SqlCommand. The following code demonstrates how to set up and execute a simple reader:
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table",
myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
Console.WriteLine(myReader["Column1"].ToString());
Console.WriteLine(myReader["Column2"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Categories