对于需要连接数据库的程序来说,如何通过程序读取数据库,操作数据库,在此,我将介绍,如何用C#程序,实现程序与数据库的连接。(参考肅Kian的文章)
1.程序刚开始运行的主界面
2.点击“连接”按钮会显示数据库的“连接状态”“数据库版本”“数据库名称”以及“显示”数据库中的数据
3.当输入用户名,密码,点击“注册”按钮后会把用户名,密码,注册时间等信息写到数据库中,并弹出注册成功提醒
4.点击断开后“程序界面”如下:
5.此程序的所有代码陈列如下: 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) {
string strCon = \Security=true \定义数据库链接字符串
string strCmd = \定义数据库操作字符串
SqlConnection conn = new SqlConnection(strCon);//实例化一个数据库链接对象 SqlDataAdapter da = new SqlDataAdapter(strCmd, conn);//将查询语句应用到数据库中
DataSet ds = new DataSet(); da.Fill(ds, \ 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[\ }
catch (Exception ex) {
MessageBox.Show(ex.ToString()); } }
private void btnRegister_Click(object sender, EventArgs e) {
string strCon = \Security=true \定义数据库链接字符串 DateTime dt = DateTime.Now;
string strCmd = \txtName.Text + \ string str = \ 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, \
dataShow.DataSource = ds.Tables[\