开发环境:
win10
SQLServer2008
VS2012
C# Win窗体应用程序与的SQL Server数据交换:
1.创建数据库myTest。
2.在数据库myTest中添加表tb_Student,字段分别为StuID,StuName
3.在vs中创建win窗体应用程序DBtestDemo。
4.在窗体中拖入控件label1,label2,textBox1,textBox2,Button1.
并设置属性(name)
txtBoxID
txtBoxName
btnInsert
5.在vs中连接数据库
6.编写代码并测试。
该字符串为数据库连接字符串 (可在数据库中直接复制)
string strConn = "数据库连接字符串";
Data Source=服务器名称
Initial Catalog=数据库名称
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DBTestDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnInsert_Click(object sender, EventArgs e)
{
string strID = txtBoxID.Text.Trim();
string strName = txtBoxName.Text.Trim();
if(strID.Length == 0 || strName.Length == 0){
MessageBox.Show("ID或者Name不能为空");
return;
}
//1 创建与Database的connection
SqlConnection conn = new SqlConnection();
string strConn = "数据库字符串";
conn.ConnectionString = strConn;
//2 创建Command命令向数据库插入输入
SqlCommand comm = new SqlCommand();
string strInster = "Insert into tb_Student (stuID,stuName) Values ('"+strID+"','"+strName+"')";
comm.Connection = conn;
comm.CommandText = strInster;
//3 显示插入是否成功
conn.Open();
int n = comm.ExecuteNonQuery();
conn.Close();
if (n > 0)
{
MessageBox.Show("数据库连接成功");
}
else {
MessageBox.Show("数据库连接失败");
}
}
}
}
7.查看数据库数据。