连接数据库

来源:互联网 发布:圣象地板 知乎 编辑:程序博客网 时间:2024/06/05 19:50
连接数据库
程序访问数据库的步骤:
       ①开始 
           引入
           using System.Data;
           using System.Data.SqlClient;
       ②应用命名空间

                加入命名空间:using System.Data.OracleClient;

           连接数据库: string conString = "data source=IP地址; Database=数据库名;

           user id=用户名; password=密码";

           OracleConnection myconnection = new OracleConnection(conString);

           myconnection.open();

       ③创建一个SqlConnection 对象
       ④打开连接
       ⑤创建一个SqlCommand对象
       ⑥获取SqlDataReader对象
       ⑦关闭SqlDataReader对象
       ⑧关闭连接
       ⑨结束
  public void Get()        {               SqlConnection con = new SqlConnection("server=.;database =BBS;Trusted_Connection=SSPI");              con.Open();              SqlCommand cmd=new SqlCommand("select*from student",con);              SqlDataReader myreader = cmd.ExecuteReader();            while (myreader.Read())        {          Console.WriteLine(myreader.GetValue(0)+" "+myreader.GetValue(1));        }            myreader.Close();            con.Close();        }         static void Main(string[]args)        {            new Test1().Get();        }    }
增删查改:
查询功能
public List<Users> select() {            List<Users> list = new List<Users>();            SqlConnection con = new SqlConnection("server=127.0.0.1;uid =                                               sa; pwd =wang;database =second");            SqlCommand cmd = new SqlCommand("select * from users", con);            con.Open();            SqlDataReader myreader = cmd.ExecuteReader();            while (myreader.Read())            {                Users u = new Users();                u.Id =(int) myreader.GetValue(0);                u.Name =(string) myreader.GetValue(1);                u.Password = (string)myreader.GetValue(2);                list.Add(u);           }
以上是今天的知识的初步了解,如果你有什么不会的话,可以来狗刨学习网上来看看,如果你想在Unity3D上大展手脚的话,可以来狗刨培训与专家咨询。
0 0
原创粉丝点击