class SQLServerConnectionTool
{
string conString = @"Data Source=bds2715212581.my3w.com;Initial Catalog=bds271521258_db;Persist Security Info=True;User ID=bds271521258;Password=123456";
string cmd = "SELECT * FROM UserInfor";
/// sql命令
SqlCommand sqlCommand;
/// sql查询语句
SqlCommand sqlSelectCommand;
/// 连接服务器
SqlConnection sqlConnection;
/// 建立数据库和dataGridView组建的桥梁-----》填充DataTable(表示数据库中一个库中的一个表)或者DataSet(表示数据库的一个库)类型
SqlDataAdapter sqlDataAdapter;
public SQLServerConnectionTool()
{
sqlConnection = new SqlConnection(conString);
sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlSelectCommand = new SqlCommand();
sqlSelectCommand.CommandText = cmd;
sqlSelectCommand.Connection = sqlConnection;
sqlDataAdapter = new SqlDataAdapter();
}
///
/// 建立一个数据库连接
///
public void serverConnetion()
{
try
{
sqlConnection.Open();
//sqlConnection.OpenAsync(cancellationToken);
}
catch (InvalidOperationException e)
{
Debug.WriteLine(e.ToString());
}
catch (SqlException e)
{
Debug.WriteLine(e.Message);
}
}
}
///
/// 执行spl语句
///
///
public void SqlCommandExeCute(string command)
{
try
{
sqlCommand.CommandText = command;
sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Debug.WriteLine("语句执行错误" + e.ToString());
}
//catch
//{
//}
}
#region sqlDataAdapter封装类查询
string selecetCmd = "SELECT * FROM UserInfor";
public DataTable DataTableSqlSelectExeCute(DataTable dataTable)
{
try
{
dataTable.Clear();
sqlCommand.CommandText = selecetCmd;
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.Fill(dataTable);
}
catch (Exception e)
{
MessageBox.Show("数据查询错误" + e.Message);
}
return dataTable;
}
string addCmd = "insert into UserInfor values({0},'{1}',{2},{3},'{4}')";
public void DataTableSqlInsertExeCute(DataTable dataTable, int userId, string name, int sex, int age, string birthday)
{
try
{
sqlCommand.CommandText = string.Format(addCmd, userId, name, sex, age, birthday);
sqlDataAdapter.InsertCommand = sqlCommand;
dataTable.Rows.Add(userId, name, sex, age, birthday);
sqlDataAdapter.Update(dataTable);
dataTable.Clear();
sqlDataAdapter.Fill(dataTable);
}
catch (Exception e)
{
MessageBox.Show("数据插入错误" + e.Message);
}
}
string delete = "DELETE FROM UserInfor WHERE UserId = {0}";
public DataTable DataTableSqlDeleteExeCute(DataTable dataTable, int row)
{
try
{
sqlCommand.CommandText = string.Format(delete, dataTable.Rows[row]["UserId"]);
sqlDataAdapter.DeleteCommand = sqlCommand;
dataTable.Rows[row].Delete();
sqlDataAdapter.Update(dataTable);
dataTable.Clear();
sqlDataAdapter.Fill(dataTable);
}
catch (Exception e)
{
MessageBox.Show("删除错误" + e.Message);
}
return dataTable;
}
上面要注意SqlDataAdapter类的InsertCommand(必须初始化sql语句(如上面sqlDataAdapter.InsertCommand = sqlCommand;))、DeleteCommand(必须初始化sql语句(如上面sqlDataAdapter.DeleteCommand = sqlCommand;))。
所有代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SQLServer
{
class SQLServerConnectionTool
{
string conString = @"Data Source=bds2715212581.my3w.com;Initial Catalog=bds271521258_db;Persist Security Info=True;User ID=bds271521258;Password=123456";
string cmd = "SELECT * FROM UserInfor";
/// sql命令
SqlCommand sqlCommand;
/// sql查询语句
SqlCommand sqlSelectCommand;
/// 连接服务器
SqlConnection sqlConnection;
/// 建立数据库和dataGridView组建的桥梁-----》填充DataTable(表示数据库中一个库中的一个表)或者DataSet(表示数据库的一个库)类型
SqlDataAdapter sqlDataAdapter;
public SQLServerConnectionTool()
{
sqlConnection = new SqlConnection(conString);
sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlSelectCommand = new SqlCommand();
sqlSelectCommand.CommandText = cmd;
sqlSelectCommand.Connection = sqlConnection;
sqlDataAdapter = new SqlDataAdapter();
}
///
/// 建立一个数据库连接
///
public void serverConnetion()
{
try
{
sqlConnection.Open();
//sqlConnection.OpenAsync(cancellationToken);
}
catch (InvalidOperationException e)
{
Debug.WriteLine(e.ToString());
}
catch (SqlException e)
{
Debug.WriteLine(e.Message);
}
}
///
/// 关闭连接,清理数据
///
public void serverClose()
{
sqlCommand = null;
sqlSelectCommand = null;
sqlDataAdapter = null;
try
{
if (sqlConnection != null)
{
sqlConnection.Close();
sqlConnection = null;
}
}
catch
{
}
}
#region SQL语句
///
/// 执行spl语句
///
///
public void SqlCommandExeCute(string command)
{
try
{
sqlCommand.CommandText = command;
sqlCommand.ExecuteNonQuery();
}
catch (Exception e)
{
Debug.WriteLine("语句执行错误" + e.ToString());
}
//catch
//{
//}
}
#region sql包装 未使用
public void SqlCommandInsertExeCute(string command)
{
SqlCommandExeCute(command);
}
public void SqlCommandDeleteExeCute(string command)
{
SqlCommandExeCute(command);
}
public void SqlCommandSelectExeCute(string command)
{
sqlCommand.CommandText = command;
List list = new List();
SqlDataReader sqlDataAdapter = sqlCommand.ExecuteReader();
//添加参数
sqlCommand.Parameters.AddRange(list.ToArray());
while (sqlDataAdapter.Read())
{
Console.WriteLine(" {0}\t\t{1}", sqlDataAdapter["用户名"], sqlDataAdapter["性别"]);
}
sqlDataAdapter.Close();
}
#endregion
#endregion
#region sqlDataAdapter封装类查询
string selecetCmd = "SELECT * FROM UserInfor";
public DataTable DataTableSqlSelectExeCute(DataTable dataTable)
{
try
{
dataTable.Clear();
sqlCommand.CommandText = selecetCmd;
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.Fill(dataTable);
}
catch (Exception e)
{
MessageBox.Show("数据查询错误" + e.Message);
}
return dataTable;
}
string addCmd = "insert into UserInfor values({0},'{1}',{2},{3},'{4}')";
public void DataTableSqlInsertExeCute(DataTable dataTable, int userId, string name, int sex, int age, string birthday)
{
try
{
sqlCommand.CommandText = string.Format(addCmd, userId, name, sex, age, birthday);
sqlDataAdapter.InsertCommand = sqlCommand;
dataTable.Rows.Add(userId, name, sex, age, birthday);
sqlDataAdapter.Update(dataTable);
dataTable.Clear();
sqlDataAdapter.Fill(dataTable);
}
catch (Exception e)
{
MessageBox.Show("数据插入错误" + e.Message);
}
}
string delete = "DELETE FROM UserInfor WHERE UserId = {0}";
public DataTable DataTableSqlDeleteExeCute(DataTable dataTable, int row)
{
try
{
sqlCommand.CommandText = string.Format(delete, dataTable.Rows[row]["UserId"]);
//sqlDataAdapter.SelectCommand = sqlSelectCommand;
sqlDataAdapter.DeleteCommand = sqlCommand;
dataTable.Rows[row].Delete();
sqlDataAdapter.Update(dataTable);
dataTable.Clear();
sqlDataAdapter.Fill(dataTable);
}
catch (Exception e)
{
MessageBox.Show("删除错误" + e.Message);
}
return dataTable;
}
///
/// 更新函数未实现
///
///
///
public DataTable DataTableSqlUpdateExeCute(DataTable dataTable)
{
sqlCommand.CommandText = "";
sqlDataAdapter.UpdateCommand = sqlSelectCommand;
sqlDataAdapter.DeleteCommand = sqlCommand;
sqlDataAdapter.Update(dataTable);
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
#endregion
~SQLServerConnectionTool()
{
serverClose();
}
}
}
然后建立一个form窗体:
窗体代码如下:
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;
namespace SQLServer
{
public partial class Form1 : Form
{
SQLServerConnectionTool sQLServerConnectionTool;
public Form1()
{
InitializeComponent();
sQLServerConnectionTool = new SQLServerConnectionTool();
sQLServerConnectionTool.serverConnetion();
dataTable = new DataTable();
dataGridView1.DataSource = dataTable;
}
string cmd = "SELECT * FROM UserInfor";
string addCmd = "insert into UserInfor values(5,'zcy',0,26,'')";
string delete = "DELETE FROM UserInfor WHERE UserId = 3";
DataTable dataTable;
private void button1_Click(object sender, EventArgs e)
{
//sQLServerConnectionTool.SqlCommandExeCute(delete);
//sQLServerConnectionTool.SqlCommandExeCute(addCmd);
//dataGridView1.DataSource = sQLServerConnectionTool.DataTableSqlDeleteExeCute(delete);
sQLServerConnectionTool.DataTableSqlSelectExeCute(dataTable);
// sQLServerConnectionTool.SqlCommandSelectExeCute(cmd);
//sQLServerConnectionTool.DataTableSqlInsertExeCute(addCmd);
//dataGridView1.DataSource = sQLServerConnectionTool.DataTableSqlSelectExeCute(cmd);
//dataGridView1.DataSource = sQLServerConnectionTool.DataTableSqlInsertExeCute(addCmd);
}
private void button2_Click(object sender, EventArgs e)
{
int row;
if(int.TryParse(textBox1.Text, out row))
sQLServerConnectionTool.DataTableSqlDeleteExeCute(dataTable,row);
}
private void button3_Click(object sender, EventArgs e)
{
if (dataTable.Columns.Count != 5)
{
MessageBox.Show("请先查询数据");
}
int userId;
int sex;
int age;
if (int.TryParse(textBox2.Text, out userId) && int.TryParse(textBox4.Text, out sex) && int.TryParse(textBox5.Text, out age))
{
sQLServerConnectionTool.DataTableSqlInsertExeCute(dataTable, userId, textBox3.Text, sex, age, textBox6.Text);
}
else
{
MessageBox.Show("数据填写错误");
}
}
private void button4_Click(object sender, EventArgs e)
{
sQLServerConnectionTool.SqlCommandExeCute(textBox7.Text); //执行sql语句
sQLServerConnectionTool.DataTableSqlSelectExeCute(dataTable); //刷新界面
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) && e.KeyChar != 8)
{
e.Handled = true;
MessageBox.Show("请输入数字");
}
//else
//{
// //
//}
}
private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) && e.KeyChar != 8)
{
e.Handled = true;
MessageBox.Show("请输入数字");
}
}
private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) && e.KeyChar != 8)
{
e.Handled = true;
MessageBox.Show("请输入数字");
}
}
}
}
上面代码需要和你设计的窗体组件对应起来。嫌麻烦可以看我的Demo。