项目中要使用到SQL Server数据库,下面简单介绍下C#如何连接SQL Server数据库:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| using System; using System.Data.SqlClient; class DBConnector { static void connectSQLServer() { string connectionString = "Server={服务器IP地址};Database={数据库名称};User Id={用户名};Password=your_password;"; using (SqlConnection connection = new SqlConnection(connectionString)) { try { connection.Open(); Console.WriteLine("连接成功!"); string sqlQuery = "SELECT * FROM table"; using (SqlCommand command = new SqlCommand(sqlQuery, connection)) using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); } } } catch (SqlException e) { Console.WriteLine("连接失败:" + e.Message); } } Console.ReadLine(); } }
|