1.建立一个控制台测试程序简单实现
using (SqlConnection conn = new SqlConnection("Server=.;database=DB_Test;uid=sa;pwd=111111")) { //查询 conn.Open(); SqlCommand cmd = new SqlCommand("select * from test", conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); Console.WriteLine("查询出条目数:" + ds.Tables[0].Rows.Count.ToString()); } using (SqlConnection conn = new SqlConnection("Server=.;database=DB_Test;uid=sa;pwd=111111")) { //删除 conn.Open(); SqlCommand cmd1 = new SqlCommand("delete from test where id=14", conn); int rows = cmd1.ExecuteNonQuery(); Console.WriteLine("删除条目数:" + rows); } Console.Read();
2.连接字符串配置在config文件中
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="ConnASK" value="Server=.;database=DB_Test;uid=sa;pwd=111111" /> </appSettings> </configuration>
读取
//数据库连接字符串(.config来配置). public static string connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnASK"]; static void Main(string[] args) { try { using (SqlConnection conn = new SqlConnection(connectionString)) { //查询 conn.Open(); SqlCommand cmd = new SqlCommand("select * from test", conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); Console.WriteLine("查询出条目数:" + ds.Tables[0].Rows.Count.ToString()); } Console.Read(); } catch (Exception) { throw; } }