这个程序是我在文库里面找的例子,自己修改了一些东西,数据库用的是Sql server 2008,代码需要经过自己的一些修改才能够运行。
完整代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace TestData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnLink_Click(object sender, EventArgs e)
{
// MessageBox.Show("错误");
string strCon = "Server=.;Database=Exercise;Trusted_Connection=SSPI";//定义数据库链接字符串
string strCmd = "select * from reg";//定义数据库操作字符串
SqlConnection conn = new SqlConnection(strCon);//实例化一个数据库链接对象
SqlDataAdapter da = new SqlDataAdapter(strCmd, conn);//将查询语句应用到数据库中
DataSet ds = new DataSet();
da.Fill(ds, "message");
try
{
conn.Open();//数据库如果连接成功就打开
//SqlDataReader dr = da.ExecuteReader();//读出数据
txtDataName.Text = conn.DataSource.ToString();//显示数据库的名称
txtState.Text = conn.State.ToString();//显示数据库链接状态
txtVersion.Text = conn.ServerVersion.ToString();//显示数据库版本
dataShow.DataSource = ds.Tables["message"];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnRegister_Click(object sender, EventArgs e)
{
//Data Source=.;Initial Catalog=Exercise;Integrated Security=true 备份
string strCon = "Server=.;Database=Exercise;Trusted_Connection=SSPI";//定义数据库链接字符串
DateTime dt = DateTime.Now;
string strCmd = "insert into reg(_name,_password,_datetime) values('" + txtName.Text + "','" + txtPwd.Text + "','" + dt + "')";
string str = "select * from reg";
try
{
SqlConnection conn = new SqlConnection(strCon);
SqlCommand com = new SqlCommand(strCmd, conn);
conn.Open();
if (com.ExecuteNonQuery() != 0)
{
SqlDataAdapter da = new SqlDataAdapter(str, conn);
DataSet ds = new DataSet();
da.Fill(ds, "message");
dataShow.DataSource = ds.Tables["message"];
MessageBox.Show("Insert Successed!");
}
else
{
MessageBox.Show("Insert Failed!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataShow_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void btnBroken_Click(object sender, EventArgs e)
{
// string strCon = "Data Source=.;Initial Catalog=register;Integrated Security=true ";
string strCon = "data source=.;initial catalog=register;integrated security=true";
SqlConnection conn = new SqlConnection(strCon);
conn.Close();
txtDataName.Text = conn.DataSource.ToString();
txtState.Text = conn.State.ToString();//显示数据库链接状态
txtVersion.Text = "关闭数据库";//显示数据库版本
dataShow.DataSource = null;//清空datagridview中的数据
}
}
}