连接数据库 [英] connect database

查看:79
本文介绍了连接数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何连接到c#和sql server中的数据库

解决方案

作为绝对最小值,构造一个SqlConnection对象并打开它。然后,您可以在使用ExecuteReader方法之前将其附加到SqlCommand。

您使用的确切语法取决于您的数据库:查看MSDN示例此处 [ ^ ]


你需要一个SqlConnection,SqlCommand,SqlDataReader(你可以使用SqlDataReader,但是让它保持简单)



现在为了连接你必须编写以下代码< br $>


  string  connectionString =    server =。; uid = Your_SQL_Username; pwd = Your_SQL_Password; database = The_Name_Of_Your_Database; 

SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand( select *来自表格,conn);

conn.Open();

SqlDataReader dr = cmd.ExecuteReader();

while (dr.Read())
{
MessageBox.Show(dr [ 0 ]的ToString()); // 表格的第一列表格
MessageBox.Show(dr [ 1 ]的ToString()); // 如果有更多列,依此类推;
// 您还可以将值存储在变量中。
// 示例int empid = Convert.ToInt16(dr [empid]);
}

conn.Close( );


how to connect to database in c# and sql server

解决方案

As an absolute minimum, construct an SqlConnection object and Open it. You can then attach that to an SqlCommand before using the ExecuteReader method.
The exact syntax you use will depend on your database: have a look at the MSDN examples Here[^]


You need an SqlConnection, SqlCommand, SqlDataReader (you can use SqlDataReader, but let''s keep it simple)

Now in order to connect you have to write the following code

string connectionString = "server=.; uid=Your_SQL_Username; pwd=Your_SQL_Password; database=The_Name_Of_Your_Database";

SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select * from tables", conn);

conn.Open();

SqlDataReader dr = cmd.ExecuteReader();

while(dr.Read())
{
     MessageBox.Show(dr[0].ToString()); // The first column of the tables Table
     MessageBox.Show(dr[1].ToString()); // If there are more columns, and so on;
     // You can also store values in a variable.
     // Example int empid = Convert.ToInt16(dr["empid"]);
}

conn.Close();


这篇关于连接数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆