标签:数据库连接
private void button1_Click(object sender, EventArgs e)
{
SqlConnection Conn = new SqlConnection("Server=192.168.2.10;Database=Fly;uid=sa;pwd=***");
Conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO [Fly].[dbo].[A](ID,ID_Name)VALUES(‘E‘,‘E项目‘)";
cmd.Connection = Conn;
cmd.ExecuteNonQuery();//这个仅仅执行SQL命令,不返回结果集,实用于建表、批量更新
Conn.Close(); // 关闭数据库连接
}
//------------------------------------------------------------------------------------------------------------------------------
private void button2_Click(object sender, EventArgs e)
{
String connsql = "Server=192.168.2.10;Database=Fly;uid=sa;pwd=***"; // 数据库连接字符串,database设置为自己的数据库名,以Windows身份验证
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = connsql;
conn.Open(); // 打开数据库连接
String sql = "select * from Fly..A"; // 查询语句
SqlDataAdapter myda = new SqlDataAdapter(sql, conn); // 实例化适配器
DataTable dt = new DataTable(); // 实例化数据表
myda.Fill(dt); // 保存数据
dataGridView1.DataSource = dt; // 设置到DataGridView中
conn.Close(); // 关闭数据库连接
}
}
catch (Exception ex)
{
MessageBox.Show("错误信息:" + ex.Message, "出现错误");
}
}
标签:数据库连接
原文地址:http://blog.51cto.com/gongxi/2120618