C#增删改查是最基本的功能,但是也容易出小问题。在这里博主提供一个可运行的源码,作为笔记的同时也希望能给予大家帮助。除此以外,还将分享一个通过导入.xls读取数据的源码。
- db.cs
首先,我们创建一个db.cs类。
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace PressureSketch
{
class db
{
public static string connectionstring = "server=localhost;database=XXX;uid=sa;pwd=111";
public static SqlConnection OpenDB()
{
try
{
SqlConnection oConn = new SqlConnection(connectionstring);
oConn.Open();
return oConn;
}
catch
{
throw;
}
}
public static void CloseDB(SqlConnection oConn)
{
try
{
oConn.Close();
}
catch
{
throw;
}
}
public static DataSet Execute(string strCommandString)
{
try
{
SqlConnection oConn = OpenDB();
DataSet oDataSet = new DataSet();
SqlDataAdapter oDataAdapter = new SqlDataAdapter(strCommandString, oConn);
oDataAdapter.Fill(oDataSet);
CloseDB(oConn);
return oDataSet;
}
catch
{
throw;
}
}
public static int ExecuteNonQuery(string strCommandString)
{
int li_count = 0;
SqlConnection oConn = null;
SqlCommand oComm = null;
try
{
oConn = new SqlConnection(connectionstring);
oComm = new SqlCommand();
oConn.Open();
oComm.Connection = oConn;
oComm.CommandText = strCommandString;
li_count = oComm.ExecuteNonQuery();
return li_count;
}
catch
{
return 0;
}
finally
{
if (oConn != null) oConn.Close();
}
}
public static int ExecuteReid(string strCommandString)
{
int li_count = 0;
SqlConnection oConn = null;
SqlCommand oComm = null;
try
{
oConn = new SqlConnection(connectionstring);
oComm = new SqlCommand();
oConn.Open();
oComm.Connection = oConn;
oComm.CommandText = strCommandString;
li_count = Convert.ToInt32(oComm.ExecuteScalar().ToString());
return li_count;
}
catch
{
return 0;
}
finally
{
if (oConn != null) oConn.Close();
}
}
}
}
- 将已有数据通过表格形式显示出来
private int get_db1(string as_where)
{
string ls_sql = "select time,p4far1 from table_test " + as_where + " order by dbid";
DataSet ds = new DataSet();
try
{
ds = db.Execute(ls_sql);
}
catch
{
//数据库出错,相应的sql为getsql()
MessageBox.Show("error of connect database");
}
dataGridView1.DataSource = ds.Tables[0].DefaultView;
dataGridView1.Columns[0].HeaderText = "时间(min)";
dataGridView1.Columns[1].HeaderText = "P4";
dataGridView1.Columns[0].Width = 150;
dataGridView1.Columns[1].Width = 150;
dataGridView1.Columns[2].Visible = false;
return ds.Tables[0].Rows.Count;
}
- 增、改数据
private void bt_save_Click(object sender, EventArgs e)
{
if (ls_dbid == "")
{
string ls_sql = "INSERT INTO table_test ( time,p4far1 ) VALUES ( @@time, @@p4far1 ); SELECT dbid FROM table_test WHERE (dbid = @@IDENTITY)";
//ls_sql = ls_sql.Replace("@@dbid", "'" + textBox4.Text.ToString() + "'");
ls_sql = ls_sql.Replace("@@time", "'" + textBox2.Text.ToString() + "'");
ls_sql = ls_sql.Replace("@@p4far1", "'" + textBox3.Text.ToString() + "'");
int li_ret1 = db.ExecuteReid(ls_sql);
if (li_ret1 > 0)
{
ls_dbid = li_ret1.ToString();
}
else
{
MessageBox.Show("增加失败", "信息");
return;
}
}
else
{
string ls_sql = "update table_test set time=@@time,p4far1=@@p4far1 where dbid = " + ls_dbid;
ls_sql = ls_sql.Replace("@@time", "'" + textBox2.Text.ToString() + "'");
ls_sql = ls_sql.Replace("@@p4far1", "'" + textBox3.Text.ToString() + "'");
db.ExecuteNonQuery(ls_sql);
}
get_db1("");
MessageBox.Show("保存成功!", "信息");
}
- 删除数据
private void bt_del_Click(object sender, EventArgs e)
{
if (ls_dbid == "")
{
MessageBox.Show("请选择要删除的记录");
}
else
{
string ls_sql = "delete from table_test where dbid=" + ls_dbid;
db.ExecuteNonQuery(ls_sql);
get_db1("");
MessageBox.Show("删除成功!", "信息");
}
}
- 查询数据
private void txt_cx_TextChanged(object sender, EventArgs e)
{
string ls_where = "";
if (this.Text.Equals(""))
{
ls_where = "";
}
else
{
ls_where = " where (time like '%" + textBox1.Text.ToString() + "%')";
//ls_where = " where (time like '%" + textBox1.Text.ToString() + "%') or (xm2 like '%" + textBox1.Text.ToString() + "%') or (xm3 like '%" + textBox1.Text.ToString() + "%')";
}
get_db1(ls_where);
}
- 左击数据进行填充
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
textBox2.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
textBox3.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
ls_dbid = dataGridView1.CurrentRow.Cells[21].Value.ToString();
}
- 导入.xls读取数据
private DataSet xsldata(string filepath)
{
string strCon = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;IMEX=1'";
System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon);
string strCom = "SELECT * FROM [Sheet1$]";
Conn.Open();
System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn);
DataSet ds = new DataSet();
myCommand.Fill(ds, "[Sheet1$]");
dataGridView1.DataSource = ds.Tables[0];
Conn.Close();
return ds;
}
private void button7_Click(object sender, EventArgs e)
{
if (textBox25.Text == "")
{
MessageBox.Show("请选择要导入的Excel文档!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string filepath = textBox25.Text;
SqlConnection conn = new SqlConnection(strcon);//链接数据库
conn.Open();
try
{
DataSet ds = new DataSet();
//取得数据集
//调用上面的函数
ds = xsldata(filepath);
//dataGridView2.DataSource = ds.Tables[0];
int errorcount = 0;//记录错误信息条数
int insertcount = 0;//记录插入成功条数
int updatecount = 0;//记录更新信息条数
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
int time = Convert.ToInt32(ds.Tables[0].Rows[i][0].ToString());
double p4far1 = Convert.ToDouble(ds.Tables[0].Rows[i][1].ToString());
double p1mid1 = Convert.ToDouble(ds.Tables[0].Rows[i][2].ToString());
if (time.ToString() != "")
{
SqlCommand selectcmd = new SqlCommand("select count(*) from table_test where time=" + time, conn);
int count = Convert.ToInt32(selectcmd.ExecuteScalar());
if (count > 0)
{
updatecount++;
}
else
{
SqlCommand insertcmd = new SqlCommand("insert into table_test(time,p4far1) values(" + time + ",'" +
p4far1 + ")", conn);
insertcmd.ExecuteNonQuery();
insertcount++;
}
}
else
{
//MessageBox.Show("电子表格信息有错!");
errorcount++;
;
}
}
MessageBox.Show(insertcount + "条数据导入成功!" + updatecount + "条数据重复!" + errorcount + "条数据部分信息为空没有导入!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
需要注意的是:string strCon = “Provider=Microsoft.Ace.OleDb.12.0;Data Source=” + filepath + “;Extended Properties=‘Excel 8.0;IMEX=1’”;这里和office版本有关,注意修改。
- 在表格前添加序号
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
DataGridView dgv = sender as DataGridView;
Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
dgv.RowHeadersWidth - 4,
e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
dgv.RowHeadersDefaultCellStyle.Font,
rectangle,
dgv.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
- 运行
最终在构造函数中调用get_db1("");即可,其中 public static string strcon = “server=localhost;database=XXX;uid=sa;pwd=111”; private string ls_dbid = “”; - 数据库设计
- .xls格式
通过.xls读取数据需注意格式,即首行字段名。
以上就是C#实现增删改查以及通过.xls读取数据的相关代码,欢迎各位交流以及指导!