ADO.net 2-database connection successful --- ShinePans,
Database Configuration:
Connection string: server = Pan Shang \ SQLEXPRESS; database = db_test; Trusted_Connection = true
Connection code:
Using System; using System. collections. generic; using System. data. sqlClient; using System. linq; using System. text; using System. threading. tasks; namespace SQLTest {class Program {static void Main (string [] args) {// connect to the database string connection = "server = Pan Shang \ SQLEXPRESS; database = db_test; trusted_Connection = true "; SqlConnection SC = new SqlConnection (); SC. connectionString = connection; try {SC. open (); Console. WriteLine ("the database connection has been enabled! ");} Catch (Exception ex) {Console. writeLine ("Opening Database Error: {0}", ex. message);} finally {SC. close (); Console. writeLine ("the database connection is closed! ") ;}System. Console. ReadLine ();}}}
Connection result:
Adonet connection to the SQL server database
Write two lines of code for you. using System. Data;
Using System. Data. SqlClient; // introduce the namespace
Public class DataLayer
{
Private static SqlConnection CreateSqlConnection ()
{
SqlConnection conn = new SqlConnection ();
Conn. ConnectionString = "server = 218.28.188.237; uid = zhiagng; pwd = ******; database = zhigang ";
Return conn;
}
}
When you need to call this connection, you can directly reference the static method of the class: do not forget to open it ......
Write an example: Get table A1 data on a webpage:
SqlConnection _ myConn = DataLayer. CreateSqlConnection ();
_ MyConn. Open (): // Open the database connection
SqlCommand _ QueryCmd = new SqlCommand ();
_ QueryCmd. Connection = _ myConn;
_ QueryCmd. CommandText = "Select * from A1 ";
SqlDataAdapter _ adpt = new SqlDataAdapter (_ QueryCmd ):
DataSet _ ds = new DataSet ();
_ Adpt. Fill (_ ds, "A1"); // The DataSet object obtains data.
When referencing data, you can:
DataView1.DataSource = _ ds. Tables [0];
DataView. DataBind (); // bind data
You can use the singleton mode for shorthand, which is easier!
ADONET database connection problems
It should be a keyword conflict
It is best not to use common words such as user and name for table naming. I used to use name to name a table, and the results were always wrong. In the end, I found that it was a naming problem.