连接数据库

步骤

  1. 引入命名空间
  2. 创建连接字符串
  3. 创建连接对象
  4. 创建sql语句字符串
  5. 创建命令对象
  6. 打开连接并执行命令
  7. 读取数据
  8. 关闭连接
数据库连接示例.png

代码

using System.Data;  //表的命名空间
using System.Data.SqlClient;  //和SQL相关

namespace 连接字符串
{
    class Program
    {
        static void Main(string[] args)
        {
            //1创建连接字符串
            //方法一
            SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
            scsb.DataSource = "localhost";  
            scsb.InitialCatalog = "AddressBook";
            scsb.IntegratedSecurity = true;  //scsb.UserID   scsb.Password
            //方法二
            //string conStr = "Data Source=localhost;Initial Catalog=AddressBook;Integrated Security=True";
            //string conStr = "Data Source=localhost;Initial Catalog=AddressBook;User ID=sa;Passwrod=123456";

            //2创建连接对象
            SqlConnection con = new SqlConnection(scsb.ToString());
            //SqlConnection con = new SqlConnection(conStr);

            //3创建sql语句
            string sql = "select * from TblPerson";

            //4创建命令对象
            SqlCommand cmd = new SqlCommand(sql, con);

            //5打开连接执行命令
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            //6读取数据
            while(reader.Read())
            {
                Console.Write(reader["姓名"].ToString());
                Console.Write("\t");
                Console.WriteLine(reader[3].ToString());
            }
            //7关闭连接
            con.Close();

            Console.ReadKey();
        }
    }
}

你可能感兴趣的:(连接数据库)