主要代码如下:

                //连接字符串
                string strConn="user id=sa;password=123456;initial catalog=MyDb;Server=192.168.47.144,1433;Connect Timeout=10";
               
                //创建连接对象
                SqlConnection objConn = new SqlConnection(strConn);

                try
                {       //开始连接数据库
                        objConn.Open();

 

                        //执行SQL语句
                        string sql = "SELECT COUNT(*) FROM tb_People";

                         

                        //创建命令对象...   
                        SqlCommand sqlCom = new SqlCommand(sql,objConn);

 

                        Console.WriteLine("\n数据库中共有{0}条记录",sqlCom.ExecuteScalar());
            
                        //断开与数据库的连接...
                        objConn.Close();
                }
                //捕获异常...
                catch(SqlException e){

                        objConn.Close();

                        Console.WriteLine(e.Message+e.ErrorCode);

                }


本文转载:CSDN博客