c#连接SQL Server 数据库

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;
            }
           
        }

 

c#连接SQL Server 数据库,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。