ADO.NET、JDBC连接Sql Server2008简单实例
来源:互联网 发布:安卓chroot运行linux 编辑:程序博客网 时间:2024/06/06 17:21
一、C#调用ADO.NET连接Sqlserver2008
(1)DB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;
namespace SqlServerProcedure
{
class DB
{
// 数据库连接字符串
private static string connString = "Data Source=localhost;Initial catalog=book;User ID=sa;Password=***";//自己的密码
// 创建 Connection 对象
public static SqlConnection connection = new SqlConnection(connString);
}
}
(2)MainForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SqlServerProcedure
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
try
{
DB.connection.Open();
DataTable mytable = new DataTable();
DataSet ds = new DataSet();
string str = "select companyid as 公司代码,companyname as 公司名称,remark as 标记 from company";
SqlDataAdapter adapter = new SqlDataAdapter(str, DB.connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Fill(ds);
mytable = ds.Tables[0];
dataGridView1.DataSource = mytable;
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
finally