I am working on my first project using local database on C#. I have searched on internet different code for inserting data, but nothing has worked for me. I am trying different code, the problem that occurs to me is the built in functions they are using doesn't show up in my code. Can someone share the authentic code for inserting, retrieving and deleting in local database ?
The recent code that I have tried, some exception is occurring in SqlCeConnection.
This is my code :
string str="Data Source=(localdb)shop_database;Initial Catalog=shop_database;Integrated Security=True";
SqlCeConnection con = new SqlCeConnection(str);
SqlCeDataAdapter sda = new SqlCeDataAdapter();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "Insert into Account_details (Account_No,Customer_name,Customer_father_name,Profession,Mobile_No,Office_Address,House_Address,CNIC,Item_name,Item_color,Item_model,Item_engine_NO,Item_chasis_NO,Cash_price,Installment_price,Advance_given,Amount_left,Monthly_Installment,Monthly_Rent,Date_of_giving,Sponsor_name,Sponsor_father_name,Sponsor_profession,Sponsor_Address,Sponsor_CNIC,Sponsor_Mobile_No) values (#Account_No,#Customer_name,#Customer_father_name,#Profession,#Mobile_No,#Office_Address,#House_Address,#CNIC,#Item_name,#Item_color,#Item_model,#Item_engine_NO,#Item_chasis_NO,#Cash_price,#Installment_price,#Advance_given,#Amount_left,#Monthly_Installment,#Monthly_Rent,#Date_of_giving,#Sponsor_name,#Sponsor_father_name,#Sponsor_profession,#Sponsor_Address,#Sponsor_CNIC,#Sponsor_Mobile_No)";
cmd.Parameters.AddWithValue("#Account_No", this.Textbox0.Text);
cmd.Parameters.AddWithValue("#Customer_name", this.Textbox1.Text);
cmd.Parameters.AddWithValue("#Customer_father_name", this.Textbox2.Text);
cmd.Parameters.AddWithValue("#Profession", this.Textbox3.Text);
cmd.Parameters.AddWithValue("#Mobile_No", this.Textbox4.Text);
cmd.Parameters.AddWithValue("#Office_Address", this.Textbox5.Text);
cmd.Parameters.AddWithValue("#House_Address", this.Textbox6.Text);
cmd.Parameters.AddWithValue("#CNIC", this.Textbox7.Text);
cmd.Parameters.AddWithValue("#Item_name", this.Textbox14.Text);
cmd.Parameters.AddWithValue("#Item_color", this.Textbox15.Text);
cmd.Parameters.AddWithValue("#Item_model", this.Textbox16.Text);
cmd.Parameters.AddWithValue("#Item_engine_NO", this.Textbox17.Text);
cmd.Parameters.AddWithValue("#Item_chasis_NO", this.Textbox18.Text);
cmd.Parameters.AddWithValue("#Cash_price", this.Textbox19.Text);
cmd.Parameters.AddWithValue("#Installment_price", this.Textbox20.Text);
cmd.Parameters.AddWithValue("#Advance_given", this.Textbox21.Text);
cmd.Parameters.AddWithValue("#Amount_left", this.Textbox25.Text);
cmd.Parameters.AddWithValue("#Monthly_Installment", this.Textbox22.Text);
cmd.Parameters.AddWithValue("#Monthly_Rent", this.Textbox23.Text);
cmd.Parameters.AddWithValue("#Date_of_giving", this.Textbox24.Text);
cmd.Parameters.AddWithValue("#Sponsor_name", this.Textbox8.Text);
cmd.Parameters.AddWithValue("#Sponsor_father_name", this.Textbox9.Text);
cmd.Parameters.AddWithValue("#Sponsor_profession", this.Textbox10.Text);
cmd.Parameters.AddWithValue("#Sponsor_Address", this.Textbox11.Text);
cmd.Parameters.AddWithValue("#Sponsor_CNIC", this.Textbox12.Text);
cmd.Parameters.AddWithValue("#Sponsor_Mobile_No", this.Textbox13.Text);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
To edit, insert, in general interact with your database you need the class SqlCommand. First you create a connection to your database with an SqlConnection object. Then you pass the SQL statement as a string and the connection into the constructor of the SqlConnection class. Little example:
SqlConnection con = new SqlConnection("server=localhost;database=test_db;uid=root;password=yourpassword");
SqlCommand cmd = new SqlCommand("select * from your_table", con);
To retreive the data from the database you need to use the SQL Statements. For example an SQL statement is something like:
insert into my_table (value1, value2)
values("Example", "Insertion");
When you created your SqlConnection and the SqlCommand you need to open the database connection and execute the command. Wether it's a command for receiving information from the database or editing the database you use ExecuteReader() or ExecuteNonQuery(). For example when you want to receive all the Information stored in one table you use:
SqlConnection con = new SqlConnection("connection string as shown above");
SqlCommand cmd = new SqlCommand("select * from example_table", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
Console.WriteLine(reader[<table_index or attribute Name>]);
And finally dont forget to call the close method on your SqlConnection and SqlDataReader object
You are probably making two mistakes:
Problem 1. Your connecting string looks like wrong. Instead of:
Data Source=(localdb)shop_database;Initial Catalog=shop_database;Integrated Security=True";
It should be:
Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=shop_database;Integrated Security=True";
Problem 2. You are not opening the connection before executing the command. Your code in the block should be like this:
try
{
conn.Open(); // Open the connection
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close(); // Close the connection
}
As a best practice, I recommend that you use "using" block to create your connection. In that case, you don't have to explicitly close the connection and set it to null:
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
conn.Open();
// Remaining code
}
}
catch(Exception ex)
{
// Manage your exception here
}
Is self signed certificate disrupting connection to mysql?
I already give action crud in data and grant access to administration.
but the connection still got error.
Unable to connect to any of the specified MySQL hosts
my team connection like this:
Catalog=devbaf;User Id=userclient;password=client123
connection code:
try
{
string constring = "SERVER=123.45.678.9;DATABASE=devbaf;User Id=backendsystem;PASSWORD=1q2w3e4r5t;";
using (MySqlConnection con = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM users"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvtest.DataSource = dt;
gvtest.DataBind();
}
}
}
}
}
catch (Exception e)
{
Response.Write(e.Message.ToString());
}
explanation problem:
I make a database in local server, so my friend can access to it to insert data. but when he make a connection script it wont connect to my database but can connect to server. He already tries to move some file to the server and it works,but the connection to database wont connect. i don't have an experience for this coz im php programmer not c# programmer. hope my explanation is clear.
I have found your error message like trying to connect the host but in your connection string is missing the MySQL server name or host address. I hope if you add the MySQL hostname or server address to your connection. it will fix your issue.
you can try this
string connectionString ="SERVER=servername; DATABASE=databasename; User Id=userid; PASSWORD=password;";
Is there anything wrong with this code? Please help me out.
protected void Button_Click(object sender, EventArgs e)
{
string cs = "Data Source=SFSIND0402;Initial Catalog=TestDB;Integrated Security=SSPI;Provider=Microsoft.ACE.OLEDB.12.0";
OleDbConnection conn = new OleDbConnection(cs);
conn.Open();
OleDbCommand insert = conn.CreateCommand();
insert.CommandText="insert into Employee(ID, Name, Sex, Salary) values('003','Vedpathi','M',25000)";
insert.Connection = conn;
insert.ExecuteNonQuery();
conn.Close();
}
I am getting the following error:
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done
(on line 22:conn.Open();)
When connecting to an MS SQL database, use the MS SQL providers:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var cmd = new SqlCommand(commandText, connection);
cmd.ExecuteNonQuery();
}
In addition to the solution Luaan mentioned, you should store your connection string in the config file of the app and also encrypt it.
Even if you use SSL encryption when communicating with the DB, an ill-indended person can extract the string variables, if he / she runs the application on his / her machine.
I'm connecting my windows form application to SQL server but I get this error "SqlException was unhandled" when I start the program.
Here is my code:
void ShowEmployees()
{
using (SqlConnection Connect = new SqlConnection("Data Source=(local);" + "Database='SanMarDryCleaners';" + "Integrated Security=SSPI;"))
{
string strEmployees = "SELECT * FROM employees;";
SqlCommand cmdEmployees = new SqlCommand(strEmployees, Connect);
SqlDataAdapter daEmployees = new SqlDataAdapter();
daEmployees.SelectCommand = cmdEmployees;
DataSet dsEmployees = new DataSet("EmployeesSet");
daEmployees.Fill(dsEmployees);
Connect.Open();
dgvEmployees.DataSource = dsEmployees;
dgvEmployees.DataMember = dsEmployees.Tables[0].TableName;
}
}
Here is the screenshot:
The error suggest that it can't find the SQL Server. And that makes sense because you are using a SqlConnection class which is for Microsoft SQL Server only. You have to use MySQL libary.
Download it from this site:
http://dev.mysql.com/downloads/connector/net/
The error points to a problem while connecting to the server.
A SqlConnection is for SQL-Servers. Use a library specific to MySQL and a MySqlConnection.
See:
Connector/Net Installation
MySQL Connector/Net connection strings
I am developing a Class Library in C# and in this Class Library I am trying to access database through ADO.NET code, But I'm getting this error. I don't know what is the reason behind it. So please tell me how can I solve it.
System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:\Users\vivek.nuna\Documents\VisualStudio2005\Projects\SubsystemSyncService\TestClient\bin\Debug\aspnetdb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
This is the connection string I am using.
<connectionStrings>
<add name="RegistrationConnString"
connectionString="Server=192.168.101.145\SQLEXPRESS;Database=***_HubDB;User Id=sa;Password={C8273EFD-LB2F-4E65-8702-14B61PI08A9}"
providerName="System.Data.SqlClient" />
</connectionStrings>
Note: I can't see a file aspnetdb.mdf in the Debug folder.
This is the code, how I am using ado.net code.
private DataSet GetAddressFieldsAccordingtoAddressId(string strAddressId)
{
try
{
strConnString = ConfigurationManager.ConnectionStrings["RegistrationConnString"].ToString();
SqlConnection connection = new SqlConnection(strConnString);
SqlCommand command = new SqlCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[PL_spPLUIGetAddressFieldsAccordingtoAddressId]";
command.Parameters.Add("#lAddressID", System.Data.SqlDbType.Int).Value = Convert.ToInt32(strAddressId);
command.Connection = connection;
DataSet dsPwd = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter(command);
dAdapter.Fill(dsPwd);
command.Dispose();
dAdapter.Dispose();
return dsPwd;
}
catch (Exception ex)
{
return null;
}
}
I have added reference of this class Library in a C# form.
C# form is calling this method of class library.
If you want a standalone database for your application, you should have a look at
SQL Server Compact : http://www.microsoft.com/sqlserver/2008/en/us/compact.aspx
SQLite : http://sqlite.phxsoftware.com/
For connectionstrings see http://www.connectionstrings.com/access-2003/.
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf;Persist Security Info=False";