源代码链接:
首先附上工程代码,方面大家自取。链接: https://pan.baidu.com/s/14mucHtweQVvm3KjnEzQNMg?pwd=8x9v
提取码:8x9v
一、创建数据库
1、创建以Database2.mdb命名的数据库。
2、打开新创建的数据库,并点击表,将表改名为information
3、 分别给表添加如下字段:姓名、国籍、电话、性别
二、winform的界面设计
三、链接数据库的代码的编写
代码编写前先要增加引用using System.Data.OleDb;否则无法使用sql语句
1、数据增加的代码实现
string oleCon = "provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:DataBase Password='';User Id='admin';Data source=|DataDirectory|Database2.mdb";
OleDbConnection conn = new OleDbConnection(oleCon);
conn.Open();
string conf = "select 姓名 from information where 姓名 = '" + this.textBox1_Name.Text + "'";
OleDbCommand cmdc = new OleDbCommand(conf, conn);
OleDbDataReader read = cmdc.ExecuteReader();
if (read.Read() == true)
{
MessageBox.Show("用户名已存在");
}
else
{
string reg = "insert into information(姓名,国籍,电话,性别) values('" + this.textBox1_Name.Text + "','" + this.textBox2_Nation.Text + "','" + this.textBox3_Phone.Text + "','" + str + "')";
OleDbCommand cmd = new OleDbCommand(reg, conn);
cmd.CommandText = reg;
cmd.ExecuteNonQuery();
}
conn.Close();
2、数据删除的代码实现
string oleCon = "provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:DataBase Password='';User Id='admin';Data source=|DataDirectory|Database2.mdb";
OleDbConnection conn = new OleDbConnection(oleCon);
conn.Open();
string jud = "select `姓名` from `information` where `姓名`='" + this.textBox1_Name.Text + "'";
OleDbCommand cmd = new OleDbCommand(jud, conn);
OleDbDataReader read = cmd.ExecuteReader();
string delsql = "Delete from `information` where `姓名` = '" + this.textBox1_Name.Text + "'";
OleDbCommand cmd2 = new OleDbCommand(delsql, conn);
cmd2.CommandText = delsql;
cmd2.ExecuteNonQuery();
3、数据修改的代码实现
string oleCon = "provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:DataBase Password='';User Id='admin';Data source=|DataDirectory|Database2.mdb";
OleDbConnection conn = new OleDbConnection(oleCon);
conn.Open();
string jud = "select `姓名` from `information` where `姓名`='" + this.textBox1_Name.Text + "'";
OleDbCommand cmd = new OleDbCommand(jud, conn);
OleDbDataReader read = cmd.ExecuteReader();
if (read.Read() == true)
{
string sqlcmd = string.Format("update information set 国籍='{0}',电话='{1}',性别='{2}' where 姓名='{3}'", this.textBox2_Nation.Text, this.textBox3_Phone.Text, str, this.textBox1_Name.Text);
OleDbCommand oleDbCommand = new OleDbCommand(sqlcmd, conn);
int i = oleDbCommand.ExecuteNonQuery();
conn.Close();
}
4、数据查询的代码实现
string str;
string sAccessConnection = "provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:DataBase Password='';User Id='admin';Data source=|DataDirectory|Database2.mdb";
OleDbConnection odcConnection = new OleDbConnection(sAccessConnection);
odcConnection.Open();
OleDbCommand odCommand = odcConnection.CreateCommand();
odCommand.CommandText = "select 姓名,国籍,电话,性别 from information";
OleDbDataReader odrReader = odCommand.ExecuteReader();
if(odrReader.Read())
{
textBox1_Name.Text = odrReader["姓名"].ToString();
textBox2_Nation.Text = odrReader["国籍"].ToString();
textBox3_Phone.Text = odrReader["电话"].ToString();
str = odrReader["性别"].ToString();
}