//用前记得导入以下命名空间,相当于Java中的包啦...
                //using System.Data.SqlClient;

 

                //设置连接数据库的用户名和密码
                string strConn="user id=sa;password=123456;";

 

                //设置连接的数据库名、数据库所在电脑的IP、端口,注意IP、端口之间以逗号相隔
                strConn+="initial catalog=MyDb;Server=192.168.47.144,1433;";

 

                //设置连接超时时间10秒
                strConn+="Connect Timeout=10";

 

                //上面相当于以下这行代码
               //string strConn="user id=sa;password=123456;initial catalog=MyDb;Server=192.168.47.144,1433;Connect Timeout=10";

 

                //创建连接对象objConn
                SqlConnection objConn = new SqlConnection(strConn);
                try
                {
                        //开始连接数据库

                        objConn.Open();

 

                        Console.WriteLine("\n连接的数据库版本为:{0}", objConn.ServerVersion);

                        Console.WriteLine("\n连接的数据库名为:{0}", objConn.Database);

                        Console.WriteLine("\n连接的数据源为:{0}", objConn.DataSource);

                        Console.WriteLine("\n连接状态为:{0}", objConn.State);

                        Console.WriteLine("\n工作站名(即运行本程序的电脑名)为:{0}", objConn.WorkstationId);

                        objConn.Close();
                }
                //捕获异常...
                catch(SqlException e){

 

                        objConn.Close();

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

                }

 

                Console.WriteLine("\n2012.03.11 Sunday By yxHuang!...");

 

                Console.Read();

 


本文转载:CSDN博客