C连接sql数据库执行简单的增删改查操作
C#访问SQLServer增删改查代码实例

C#访问SQLServer增删改查代码实例⼀个专门实现访问sql server数据库增删改查的操作代码,分享给⼤家,具体内容如下using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data;using System.Data.SqlClient;namespace WindowsFormsApplication1{public partial class Form1 : Form{public Form1(){InitializeComponent();}//查询private void button1_Click(object sender, EventArgs e){string MyConn = "server=127.0.0.1;uid=sa;pwd=123654;database=libbook;Trusted_Connection=no";//定义数据库连接参数 SqlConnection MyConnection = new SqlConnection(MyConn);//定义⼀个数据连接实例SqlCommand MyCommand = new SqlCommand("SELECT * FROM 图书借阅", MyConnection); //定义⼀个数据库操作指令 SqlDataAdapter SelectAdapter = new SqlDataAdapter();//定义⼀个数据适配器SelectAdapter.SelectCommand = MyCommand;//定义数据适配器的操作指令DataSet MyDataSet = new DataSet();//定义⼀个数据集MyConnection.Open();//打开数据库连接SelectAdapter.SelectCommand.ExecuteNonQuery();//执⾏数据库查询指令MyConnection.Close();//关闭数据库SelectAdapter.Fill(MyDataSet);//填充数据集DataGrid1.DataSource = MyDataSet.Tables[0];//DataGrid1.DataBind();//将数据表格⽤数据集中的数据填充}//添加private void button2_Click(object sender, EventArgs e){string MyConn = "server=127.0.0.1;uid=sa;pwd=123654;database=libbook;Trusted_Connection=no";SqlConnection MyConnection = new SqlConnection(MyConn);string MyInsert = "insert into 图书借阅 (图书编号,读者编号,续借次数) values ('" + Convert.ToString(textBox2.Text) + "','" + Convert.ToString(textBox3.Text)+ "','"+Convert.ToInt32(textBox4.Text)+ "')";SqlCommand MyCommand = new SqlCommand(MyInsert, MyConnection);try//异常处理{MyConnection.Open();MyCommand.ExecuteNonQuery();MyConnection.Close();}catch (Exception ex){MessageBox.Show(ex.Message);}}//更新private void button3_Click(object sender, EventArgs e){string MyConn = "server=127.0.0.1;uid=sa;pwd=123654;database=libbook;Trusted_Connection=no";SqlConnection MyConnection = new SqlConnection(MyConn);string MyUpdate = "Update 图书借阅 set 操作员='" + textBox2.Text + "'" + " where 借阅编号=" + "'" + textBox1.Text + "'"; SqlCommand MyCommand = new SqlCommand(MyUpdate, MyConnection);try{MyConnection.Open();MyCommand.ExecuteNonQuery();MyConnection.Close();textBox1.Text = "";}catch (Exception ex){MessageBox.Show(ex.Message);}}//删除private void button4_Click(object sender, EventArgs e){string MyConn = "server=127.0.0.1;uid=sa;pwd=123654;database=libbook;Trusted_Connection=no"; SqlConnection MyConnection = new SqlConnection(MyConn);string MyDelete = "Delete from 图书借阅 where 借阅编号=" + textBox1.Text;SqlCommand MyCommand = new SqlCommand(MyDelete, MyConnection);try{MyConnection.Open();MyCommand.ExecuteNonQuery();MyConnection.Close();textBox1.Text = "";}catch (Exception ex){MessageBox.Show(ex.Message);}}}}数据库如下;winform中查询成功;插⼊时,因为借阅编号为⾃增,不能插⼊值,会⾃⼰⽣成;更新,外键冲突;插⼊的图书编号为000999,⽆此图书,故出错;插⼊成功;更新操作员为"王⽼师";删除借阅编号为31的记录;以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
c数据库的增删改查项目案例

c数据库的增删改查项目案例一、项目准备。
1. 得包含SQLite相关的头文件。
SQLite有个方便的C接口,我们这样写:`#include <stdio.h>`:这是标准输入输出头文件,用于在控制台打印信息啥的。
`#include <sqlite3.h>`:这个就是SQLite数据库操作的关键头文件啦。
2. 然后呢,定义一个数据库连接对象。
就像你要跟数据库交朋友,得有个联系方式一样。
`sqlite3 db;`.二、连接数据库(这就像是给数据库打电话)1. 我们使用`sqlite3_open`函数来打开数据库。
如果数据库不存在,SQLite会自动创建一个。
比如我们创建一个名为`test.db`的数据库(这名字就很普通,就像大街上随便一个名字一样)。
代码是这样的:`int rc = sqlite3_open("test.db", &db);`.如果`rc`不等于`SQLITE_OK`(这是SQLite定义的一个常量,表示操作成功),那就说明出问题了,可能是文件权限问题或者磁盘满了之类的(就像打电话占线或者号码不存在一样)。
我们可以这样处理错误:`if (rc!= SQLITE_OK) {`.`fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));`.`sqlite3_close(db);`.`return 1;`.`}`.三、创建表(这就像是给数据库盖房子,先把房子结构规划好)1. 我们要创建一个表,就像在数据库这个大社区里盖一栋楼。
假设我们要创建一个存储用户信息的表,有`id`(就像用户的身份证号,独一无二的)、`name`(用户的名字)和`age`(用户的年龄)这几个字段。
我们用SQL语句来创建这个表,SQL语句就像是给数据库下达的建筑蓝图指令。
visualstudio2019连接SQLServer数据库,增删改查详细教程(C#代码)

visualstudio2019连接SQLServer数据库,增删改查详细教程(C#代码)⼯具:1.Visual Studio 20192.SQL Server数据库(我使⽤的2008)操作:1.打开SQL Server,打开后会看到数据库的初始链接界⾯。
(如下图)2..复制上图中的“服务器名称”,然后点击“连接”,进⼊数据库。
3.打开vs,创建好⾃⼰要⽤的项⽬,我写的项⽬名称叫做:‘finnal_test’,要做的是数据库综合实习关于奖学⾦评定的管理系统4.⼯具->连接到数据库->在服务器名⾥⾯,粘贴复制的服务器名5.在下⾯选择⾃⼰要连接的数据库名称(也可以⼿动输⼊,我连接的是我⾃⼰创建的数据库:shaohui),确定6.打开“服务器资源管理器”,会看到有下图信息,点击“表”可以看到数据库⾥⾯创建的数据表连接代码:完成上述操作后只是把数据库添加到了vs⾥,要想在项⽬⾥对数据库进⾏编辑,还需要写⼀些代码。
1.打开⾃⼰的项⽬,选择项⽬->添加类类名⾃⼰起,我这⾥是SQLServerDataBase2.打开类⽂件,写⼊以下代码。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.SqlClient;using System.Threading.Tasks;//必要的命名空间namespace finnal_test{class SQLServerDataBase//MySqlCon部分,每个⼈不相同,后⾯我会进⾏说明,下⾯的是我计算机相应的配置private string MySqlCon = "Data Source=DESKTOP-8LDERGD\\SQLEXPRESS;Initial Catalog = shaohui; Integrated Security = True";public DataTable ExecuteQuery(string sqlStr)//⽤于查询;其实是相当于提供⼀个可以传参的函数,到时候写⼀个sql语句,存在string⾥,传给这个函数,就会⾃动执⾏。
在 C# 中使用 SQL 执行增删查改操作

在C# 中使用SQL 执行增删查改操作,通常需要使用SqlConnection连接数据库,SqlCommand执行SQL 语句,以及SqlDataReader读取查询结果。
以下是一个简单的示例,展示了如何使用C# 进行增删查改操作。
1. 添加必要的命名空间首先,确保你已经添加了必要的命名空间:using;using..;2. 连接字符串定义数据库连接字符串:string="Server=your_server_name;Database=your_database_na me;User Id=your_username;Password=your_password;";3. 插入数据(Insert)public void InsertData(string,int){using(SqlConnection=new SqlConnection()) {string="INSERT INTO Users (Name, Age) VALUES (@Nam e, @Age)";SqlCommand=new SqlCommand(,);..AddWithValue("@Name",);..AddWithValue("@Age",);.Open();int=.ExecuteNonQuery();.WriteLine($"{}row(s) inserted.");}}4. 删除数据(Delete)public void DeleteData(int){using(SqlConnection=new SqlConnection()) {string="DELETE FROM Users WHERE Id = @Id";SqlCommand=new SqlCommand(,);..AddWithValue("@Id",);.Open();int=.ExecuteNonQuery();.WriteLine($"{}row(s) deleted.");}}5. 查询数据(Select)public void SelectData(){using(SqlConnection=new SqlConnection()) {string="SELECT * FROM Users";SqlCommand=new SqlCommand(,);.Open();SqlDataReader=.ExecuteReader();while(.Read()){int=.GetInt32(0);string=.GetString(1);int=.GetInt32(2);.WriteLine($"Id: {}, Name: {}, Age: {}");}.Close();}}6. 更新数据(Update)public void UpdateData(int,string,int){using(SqlConnection=new SqlConnection()) {string="UPDATE Users SET Name = @Name, Age = @Age WHERE Id = @Id";SqlCommand=new SqlCommand(,);..AddWithValue("@Name",);..AddWithValue("@Age",);..AddWithValue("@Id",);.Open();int=.ExecuteNonQuery();.WriteLine($"{}row(s) updated.");}}7. 调用示例class Program{static void Main(string[]){string="Server=your_server_name;Database=your_dat abase_name;User Id=your_username;Password=your_password;";// 插入数据InsertData("John Doe",30);// 查询数据SelectData();// 更新数据UpdateData(1,"Jane Doe",28);// 删除数据DeleteData(1);}}注意事项1.异常处理:在实际应用中,建议添加异常处理机制,以捕获和处理可能出现的异常。
C#--SqlServer--增删改的操作

C#--SqlServer--增删改的操作以下是学习笔记:⼀,增加1,Command对象:添加://编写连接字符串string conString = "Server=.;DataBase=StudentManageDB;Uid=sa;Pwd=123";//创建连接对象SqlConnection conn = new SqlConnection(conString);//组合SQL语句string sql = "insert into Students (StudentName,Gender,DateOfBirth,StudentIdNo,Age,";sql += "PhoneNumber,StudentAddress,ClassId)";sql += " values('{0}','{1}','{2}',{3},{4},'{5}','{6}',{7})";//⾮值类型要加上''单引号sql = string.Format(sql, "王⼩路", "男", "1990-09-18", 120226************,23, "022-********", "天津市静海县", 2);//创建Command对象//SqlCommand cmd = new SqlCommand();//mandText = sql;//cmd.Connection = conn;SqlCommand cmd = new SqlCommand(sql, conn);//打开连接conn.Open();//执⾏操作int result = cmd.ExecuteNonQuery();//及时关闭连接conn.Close();if (result == 1) Console.WriteLine("插⼊成功!");else Console.WriteLine("插⼊失败!");Console.ReadLine();⼆,修改和删除//编写连接字符串string conString = "Server=.;DataBase=StudentManageDB;Uid=sa;Pwd=123"; //创建连接对象SqlConnection conn = new SqlConnection(conString);//组合SQL语句string sql = "update Students set StudentName='{0}' where StudentId={1}";sql = string.Format(sql, "王⼩路", 100009);//创建Command对象SqlCommand cmd = new SqlCommand(sql, conn);//打开连接conn.Open();//执⾏操作int result = cmd.ExecuteNonQuery();//执⾏操作//及时关闭连接conn.Close();if (result == 1) Console.WriteLine("修改成功!");else Console.WriteLine("修改失败!");Console.ReadLine();//编写连接字符串string conString = "Server=.;DataBase=StudentManageDB;Uid=sa;Pwd=123"; //创建连接对象SqlConnection conn = new SqlConnection(conString);//组合SQL语句string sql = "delete from Students where StudentId=" + 100022;//创建Command对象SqlCommand cmd = new SqlCommand(sql, conn);//打开连接conn.Open();//执⾏操作int result = cmd.ExecuteNonQuery();//执⾏操作//及时关闭连接conn.Close();if (result == 1) Console.WriteLine("删除成功!");else Console.WriteLine("删除失败!");Console.ReadLine();提交多条SQL语句//使⽤ExcuteNonQuery⽅法同时执⾏多条SQL语句static void Main(string[] args){string conString = "Server=.;DataBase=StudentManageDB;Uid=sa;pwd=123";SqlConnection conn = new SqlConnection(conString);//组合SQL语句string sql = "insert into Students (StudentName,Gender,DateOfBirth,StudentIdNo,";sql += "Age,PhoneNumber,StudentAddress,ClassId)";sql += " values('{0}','{1}','{2}',{3},{4},'{5}','{6}',{7})";string sql1 = string.Format(sql, "王⼩路", "男", "1990-09-18", 120226************,23, "022-********", "天津市静海县", 2);string sql2 = string.Format(sql, "王⼩刚", "男", "1992-04-15", 120226************,23, "022-********", "天津市河西区", 1);string sql3 = "update Students set StudentName='{0}' where StudentId={1}";sql3 = string.Format(sql3, "王⼩美", 100009);//将不同的SQL语句使⽤分号连接在⼀起string manySql = sql1 + ";" + sql2 + ";" + sql3;SqlCommand cmd = new SqlCommand(manySql, conn);conn.Open();int result = cmd.ExecuteNonQuery();//执⾏操作conn.Close();if (result == 3) Console.WriteLine("操作成功!");else Console.WriteLine("操作失败!");Console.ReadLine();} 获取标识列的值:新员⼯办卡后要告诉他卡号string connString = "Server=.;DataBase=StudentManageDB;Uid=sa;Pwd=123";SqlConnection conn = new SqlConnection(connString);//组合SQL语句,要求同时执⾏insert和selectstring sql = "insert into Students (StudentName,Gender,DateOfBirth,StudentIdNo,Age,PhoneNumber,StudentAddress,ClassId)"; sql += " values('{0}','{1}','{2}',{3},{4},'{5}','{6}',{7});select @@identity";sql = string.Format(sql, "李⼤国", "男", "1993-05-18", 120226************,23, "022-********", "天津市红桥区", 3);SqlCommand cmd = new SqlCommand(sql, conn);conn.Open();object newStuId = cmd.ExecuteScalar(); //使⽤Scalar⽅法同时执⾏insert和select操作conn.Close();Console.WriteLine("新增加学员的学号:{0}", newStuId);Console.ReadLine(); 增删改的操作步骤总结。
C#--SQLserver数据库基本操作(增、删、改、查)

C#--SQLserver数据库基本操作(增、删、改、查)写在前⾯:常⽤数据库:SQLserver:Oracle:MySQL:Access:在⽇常的⼯作中,通常⼀个项⽬会⼤量⽤的数据库的各种基本操作。
SQLserver数据库是最为常见的⼀种数据库,本⽂则主要是记录了C#对SQL的连接、增、删、改、查的基本操作,如有什么问题还请各位⼤佬指教。
后续也将对其他⼏个常⽤的数据库进⾏相应的整理,链接已经附在⽂章开始。
话不多说,开始码代码。
引⽤:using System.Data; //DataSet引⽤集using System.Data.SqlClient; //sql引⽤集先声明⼀个SqlConnection便于后续使⽤。
private SqlConnection sql_con;//声明⼀个SqlConnectionsql打开:///<summary>/// SQLserver open///</summary>///<param name="link">link statement</param>///<returns>Success:success; Fail:reason</returns>public string Sqlserver_Open(string link){ try { sql_con = new SqlConnection(link); sql_con.Open(); return"success"; } catch (Exception ex) { return ex.Message; }}sql关闭:///<summary>/// SQLserver close///</summary>///<returns>Success:success Fail:reason</returns>public string Sqlserver_Close(){ try { if (sql_con == null) { return"No database connection"; } if (sql_con.State == ConnectionState.Open || sql_con.State == ConnectionState.Connecting) { sql_con.Close(); sql_con.Dispose(); } else { if (sql_con.State == ConnectionState.Closed) { return"success"; } } return"success"; } catch (Exception ex) { return ex.Message; }}sql的增删改:///<summary>/// SQLserver insert,delete,update///</summary>///<param name="sql">insert,delete,update statement</param>///<returns>Success:success + Number of affected rows; Fail:reason</returns> public string Sqlserver_Insdelupd(string sql){ try { int num = 0; if (sql_con == null) { return"Please open the database connection first"; } if (sql_con.State == ConnectionState.Open) { SqlCommand sqlCommand = new SqlCommand(sql, sql_con); num = sqlCommand.ExecuteNonQuery(); } else { if (sql_con.State == ConnectionState.Closed) { return"Database connection closed"; } if (sql_con.State == ConnectionState.Broken) { return"Database connection is destroyed"; } if (sql_con.State == ConnectionState.Connecting) { return"The database is in connection"; } } return"success" + num; } catch (Exception ex) { return ex.Message.ToString(); }}sql的查:///<summary>/// SQLserver select///</summary>///<param name="sql">select statement</param>///<param name="record">Success:success; Fail:reason</param>///<returns>select result</returns>public DataSet Sqlserver_Select(string sql, out string record){ try { DataSet dataSet = new DataSet(); if (sql_con == null) { record = "Please open the database connection first"; return dataSet; }if (sql_con.State == ConnectionState.Open) { SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql, sql_con); sqlDataAdapter.Fill(dataSet, "sample"); sqlDataAdapter.Dispose(); record = "success"; return dataSet; return dataSet; } if (sql_con.State == ConnectionState.Broken) { record = "Database connection is destroyed"; return dataSet; } if (sql_con.State == ConnectionState.Connecting) { record = "The database is in connection"; return dataSet; } record = "ERROR"; return dataSet; } catch (Exception ex) { DataSet dataSet = new DataSet(); record = ex.Message.ToString(); return dataSet; }}⼩编发现以上这种封装⽅式还是很⿇烦,每次对SQL进⾏增删改查的时候还得先打开数据库,最后还要关闭,实际运⽤起来⽐较⿇烦。
c#操作数据库的增删改查语句及DataGridView简单使用
c#操作数据库的增删改查语句及DataGridView简单使⽤下⾯是要⽤户名和密码连接数据库的操作:⼀、定义连接字符串,⽤来链接SQL Serverstring str_con = "server=.(服务器名称⼀般为 . );database=WordBook(数据库名称);uid=sa(服务器登录名);pwd=123(服务器密码)";⼆、有了链接字符串之后,开始数据库操作1、数据库查询定义了⼀个查询⽅法,⽤来调⽤:public DataSet queryDatabase(string sql) //sql是查询语句{//储存数据的⼯具初始化DataSet ds = new DataSet();//相当于链接数据库的⼀个⼯具类(连接字符串)using (SqlConnection con = new SqlConnection(str_con)){con.Open(); //打开//⽤SqlConnection⼯具链接数据库,在通过sql查询语句查询结果现存⼊sql适配器SqlDataAdapter sda = new SqlDataAdapter(sql,con); //(查询语句和连接⼯具)sda.Fill(ds); //将适配器数据存⼊DataSet⼯具中con.Close(); //⽤完关闭SqlConnection⼯具return ds;}}在需要查询数据库的地⽅调⽤此⽅法:private void query() {//查询WordBook表中,book_key字段数值为7的那⼀⾏数据//string sql = "select * from Word_Book where book_key='7'";string sql = "select * from Word_Book "; //查询全表DataSet ds = help.queryDatabase(sql); //查询到数据DataTable dt = ds.Tables[0]; //把查到的数据存⼊数据表中sqlDataResult.DataSource = dt; //把数据赋值给gridView展⽰(全表)// string str=dt.Rows[0][1].ToString();//查找表中某⼀个内容// MessageBox.Show(str);}2、数据库添加、删除、修改C#中数据库的添加、删除、修改⽤的是同断代码,所以定义了⼀个⽅法,⽤来调⽤:public int changeSqlData(String sql){using(SqlConnection con=new SqlConnection(str_con)){con.Open();//操作数据库的⼯具SqlCommandSqlCommand cmd = new SqlCommand(sql, con);//(操作语句和链接⼯具)int i=cmd.ExecuteNonQuery();//执⾏操作返回影响⾏数()con.Close();return i;}}在需要操作数据库的地⽅调⽤此⽅法:①数据库添加:private void btn_add_Click(object sender, EventArgs e){//sql添加数据 insert into 表名(字段,字段...) values(‘内容’,‘内容’...)string sql = "insert into Word_Book(book_word_CN,book_word_JP,book_word_Roma,book_nominal," +"book_gloze) values('" + book_word_CN.Text.Trim()+"','"+ book_word_JP .Text.Trim() + "','"+ book_word_Roma .Text.Trim() + "','"+ book_nominal.Text.Trim() + "','" + book_gloze.Text.Trim() + "')";int i=help.changeSqlData(sql);if (i == 0) MessageBox.Show("添加失败", "提⽰:");else MessageBox.Show("添加成功", "提⽰:");}②数据库删除:private void btn_delete_Click(object sender, EventArgs e){//根据同个字段中不同内容删除多⾏//delete from Word_Book where book_key in (1,2,3)//sql删除数据delete 表名 where 字段='内容'单个条件⽤or链接,多个条件⽤and链接string sql = "delete from Word_Book where book_key='"+book_key.Text.Trim()+"'";int i=help.changeSqlData(sql);if (i == 0) MessageBox.Show("删除失败", "提⽰:");else MessageBox.Show("删除成功", "提⽰:");}②数据库更新:private void btn_update_Click(object sender, EventArgs e){//根据条件修改多个字段内容//update 表名 set 字段='内容', 字段='内容' where 条件字段='内容'string sql = "update Word_Book set book_word_CN='"+book_word_CN.Text.Trim()+"', book_word_JP='"+book_word_JP.Text.Trim()+"'where book_key='" + book_key.Text.Trim()+"'";int i = help.changeSqlData(sql);if (i == 0) MessageBox.Show("修改失败", "提⽰:");else MessageBox.Show("修改成功", "提⽰:");}3、数据库事务操作数据库⽤数据库事务相当于把数据库操作捆绑执⾏,只要其中⼀条sql语句失败,直接返回,不进⾏数据库操作,只有全部执⾏正确,才会更新数据库。
C#进行Sqlserver数据库增删查改操作
C#连接SQL Server数据库并进展增删查改操作详细代码在下边,直接可以使用设计好的C#界面:Form Les 图Form2.es i 31For4n3.es 更Progyrn心共3个窗体。
数据库:13 lj Student因」•数据,库黄系團曰i」轰0 _□至统表田口W bo星本信息妾® LJ 1EB£■亠同女诃® Qi可竊tl性匡口Service Broker 国L J ffliSE 口宾全怪运行后的界面代码:〔Forml〕publicpartialclasS^orml : Form{public Form1(){In itializep onen t();}privatevoid butt on 1_Click( object sen der, Even tArgs e){Form1_Load(se nder, e);}privatevoid Form1_Load(object sen der,Eve ntArgs e){try{SqlC onn ecti on conn = n ewSqlC onn ection(); string str = "Data Source=ZWEIQUAN-PC;Initial Catalog=Student;Integrated Security=True" conn.ConnectionString = str;conn.Open();Sqlmand cmd = newSqlmand();cmd.mandText = "select * from 根本信息表";cmd.Connection = conn;SqlDataAdapter sda = newSqlDataAdapter(cmd); DataSet ds = newDataSet();sda.Fill(ds, "根本信息表");this.dataGridView1.DataSource = ds; this.dataGridView1.DataMember = " 根本信息表";this.dataGridView1.AutoGenerateColumns = true;for (int i = 1; i < this.dataGridView1.ColumnCount; i++){ this.dataGridView1.Columns[i].DefaultCellStyle.SelectionBackColor = Color.White; this.dataGridView1.Columns[i].DefaultCellStyle.SelectionForeColor = Color.Black;this.dataGridView1.Columns[i].ReadOnly = true;}conn.Close();} catch(Exception ee){MessageBoxShow("错误:"+ ee.Message,"错误");}}privatevoid button2_Click(object sender, EventArgs e){if (this.dataGridView1.SelectedCells==null){MessageBoxShow("请选择要删| 除的项!","错误”,MessageBoxButtonsOK,MessageBoxIcon.Error);}else{if (this.dataGridView1.CurrentCell.ColumnIndex == 0){string st = this.dataGridView1[1, this .dataGridView1.CurrentCell.RowIndex].Value.ToString (); SqlConnection conn = newSqlConnection();string str = "Data Source=ZWEIQUAN-PC;Initial Catalog=Student;Integrated Security=True"conn.ConnectionString = str;conn.Open();Sqlmand cmd = newSqlmand();cmd.mandText = "delete from 根本信息表where ='" + st + "'"; cmd.Connection =conn;cmd.ExecuteNonQuery();conn.Close();}}}privatevoid button3_Click( object sender, EventArgs e){if (this.textBox1.Text.Trim() == ""){MessageBoxShow("请输入要查询的!","提示”);}else{SqlConnection conn = newSqlConnection();string str = "Data Source=ZWEIQUAN-PC;Initial Catalog=Student;Integrated Security=True"conn.ConnectionString = str; conn.Open();Sqlmand cmd = newSqlmand();cmd.mandText = "select * from 根本信息表where ='" + this.textBox1.Text.Trim() + "'";cmd.Connection = conn;SqlDataAdapter sda = newSqlDataAdapter(cmd);DataSet ds = newDataSet();sda.Fill(ds);this.dataGridView1.DataSource = ds; this.dataGridView1.DataMember = ds.Tables[0].ToString();this.dataGridView1.AutoGenerateColumns = true;conn.Close();}}privatevoid button4_Click(object sender, EventArgs e){Form2 f = newForm2();f.Show();}privatevoid button5_Click(object sender,EventArgs e){Form3 f = newForm3();f.id = Convert.ToInt32( this.dataGridView1[0,this.dataGridView1.CurrentCell.RowIndex].Value.ToString());f.Show();}}(Form2)publicpartialclassForm2 : Form{public Form2(){Initializeponent();}privatevoid Form2_Load( object sender,EventArgs e){boBox1.ltems.Add(”男”);boBox1.ltems.Add(” 女");boBox2」tems.Add(” 计算机11-1 班");boBox2」tems.Add(” 计算机11-2 班");boBox2」tems.Add(” 计算机11-3 班");boBox1.DropDownStyle = boBoxStyle.DropDownList;boBox2.DropDownStyle = boBoxStyle.DropDownList; get_bh();}privatevoid get_bh(){SqlConnection conn = newSqlConnection();string str = "Data Source=ZWElQUAN-PC;lnitial Catalog=Student;lntegrated Security=True"conn.ConnectionString = str;conn.Open();Sqlmand cmd = newSqlmand(); cmd.mandText = "select * from 根本信息表";//cmd.mandText = "select isnull(max( 编号),0)+1 from 根本信息表"; cmd.Connection = conn; SqlDataAdapter sda = newSqlDataAdapter(cmd);DataSet ds = newDataSet();sda.Fill(ds);int t = ds.Tables[0].Rows.Count;int bh = t - 1;this.textBox1.Text = (Int32 .Parse(ds.Tables[0].Rows[bh][编号"].ToString()) + 1).ToString();//this.textBox1.Text = cmd.ExecuteScalar().ToString();conn.Close();privatevoid button1_Click( object sender, EventArgs e){if (textBox2.Text.Trim() == "" || textBox3.Text.Trim() == "" || boBox1.Text.Trim() == "" || boBox2.Text.Trim() == ""){MessageBoxShow("请输入完整信息!”,”错误”,MessageBoxButtonsOK, MessageBoxIconError);}else{string str1 = textBox3.Text.Trim();int l = str1.Length;for (int i = 0; i < l; i++){if (!char.IsNumber(str1[i])){MessageBoxShow("年龄输入有误!","错误", MessageBoxButtonsOK, MessageBoxIconError);textBox3.SelectAll(); textBox3.Focus();return;}}SqlConnection conn = newSqlConnection(); string str = "Data Source=ZWEIQUAN-PC;InitialCatalog=Student;Integrated Security=True" ; conn.ConnectionString = str;conn.Open();Sqlmand cmd = newSqlmand();cmd.mandText = "insert into根本信息表(编号,性别,年龄班级)values编号” 性别,年龄,班级)";cmd.Connection = conn;cmd.Parameters.Add"编号”,SqlDbType.l nt); cmd.Parameters.Add("",SqlDbType.NVarChar, 50);cmd.Parameters.Add"性别", SqlDbType.NVarChar, 50); cmd.Parameters.Add"年龄",SqlDbType.I nt);cmd.Parameters.Add"班级", SqlDbType.NVarChar, 50); cmd.Parameters"编号"].Value = textBox1.Text.Trim(); cmd.Parameters"["].Value = textBox2.Text.Trim();cmd.Parameters"性别"].Value = boBox1.Text.Trim(); cmd.Parameters"年龄"].Value= textBox3.Text.Trim(); cmd.Parameters"班级"].Value = boBox2.Text.Trim();cmd.ExecuteNonQuery();conn.Close();this.Close();}privatevoid button2_Click( object sender, EventArgs e) {this.Close();}}(Form3)publicpartialclassForm3 : Form{public Form3(){Initializeponent();}publicint id;privatevoid Form3_Load( object sender,EventArgs e){textBox1.Text = id.ToString();SqlConnection conn = newSqlConnection("Data Source=ZWEIQUAN-PC;InitialCatalog=Student;Integrated Security=True");Sqlmand cmd = newSqlmand();cmd.Connection = conn;conn.Open();cmd.mandText = "select * from 根本信息表where 编号=" + id.ToString(); SqlDataAdapter sda = newSqlDataAdapter(cmd);DataSet ds = newDataSet();sda.Fill(ds);if (ds.Tables[0].Rows.Count == 1){this.textBox2.Text = (ds.Tables[0].Rows[0]["" ].ToString());this.textBox3.Text = (ds.Tables[0].Rows[0][” 性别”].ToStri ng());this.textBox4.Text = (ds.Tables[0].Rows[0][” 年龄”].ToStri ng());this.textBox5.Text = (ds.Tables[0].Rows[0『班级"].ToStri ng()); conn.Close();}}privatevoid button1_Click( object sender, EventArgs e){ if (textBox2.Text.Trim() == "" || textBox3.Text.Trim() == "" || textBox4.Text.Trim() == "" || textBox5.Text.Trim() == ""){MessageBoxShow("请输入完整信息!”,”错误”,MessageBoxButtonsOK, MessageBoxIconError);}else{string str1 = textBox4.Text.Trim();int l = str1.Length;for (int i = 0; i < l; i++){if (!char.IsNumber(str1[i])){MessageBoxShow("年龄输入有误!","错误", MessageBoxButtonsOK, MessageBoxIconError);textBox4.SelectAll(); textBox4.Focus();return;}}SqlConnection conn = newSqlConnection(); string str = "Data Source=ZWEIQUAN-PC;InitialCatalog=Student;Integrated Security=True" ; conn.ConnectionString = str;conn.Open();Sqlmand cmd = newSqlmand();cmd.mandText = "update 根本信息表set 编号=编号,=,性别=性别,年龄= 年龄,班级=班级where 编号=编号";cmd.Connection = conn; cmd.Parameters.Add(" 编号", SqlDbType . I nt) ;cmd.Parameters.Add("", SqlDbType.NVarChar, 50);cmd.Parameters.Add(" 性别", SqlDbType.NVarChar, 50); cmd.Parameters.Add"年龄”,SqlDbType.l nt);cmd.Parameters.Add(" 班级", SqlDbType.NVarChar, 50); cmd.Parameters"编号"].Value = textBox1.Text.Trim(); cmd.Parameters"["].Value = textBox2.Text.Trim();cmd.Parameters"性别"].Value = textBox3.Text.Trim(); cmd.Parameters"年龄"].Value= textBox4.Text.Trim(); cmd.Parameters"班级"].Value = textBox5.Text.Trim(); cmd.ExecuteNonQuery(); conn.Close();this.Close();}privatevoid button2_Click( object sender, EventArgs e){ this.Close();}}注:"Data Source= ZWEIQUAN-PC ;Initial Catalog= Student;Integrated Security=True" ZWEIQUAN-PC :计算机名Student:对应的数据库名称。
CC++语言操作sqlite数据库(增删改查)
CC++语⾔操作sqlite数据库(增删改查)在某项⽬中,需要在前端相机中做⼈脸⽐对,因此需要在前端相机中增加⼀个⼈脸底库,⼈脸底库由uuid和⼈脸特征值组成。
其中特征值为512个float 数据,移植sqlite⽤来保存底库信息,⾸先写了⼀个demo,验证可⾏性之后应⽤到实际项⽬中sqlite3 * db= NULL;int rc = 0;char * sql = new char[800];//这个要适当的申请⼤⼀点,要不然不够⽤。
char * zErrMsg = NULL;string id1 = "aaa";//⽤来模拟32位的uuid.std::vector<float> feature1{0.12, 0.23, 0.34, 0.45, 0.56, 0.67};//⽤来模拟512个⼈脸特征值.string id2 = "bbb";//⽤来模拟32位的uuid.std::vector<float> feature2{1.12, 1.23, 1.34, 1.45, 1.56, 1.67};//⽤来模拟512个⼈脸特征值.string id3 = "ccc";//⽤来模拟32位的uuid.std::vector<float> feature3{2.12, 2.23, 2.34, 2.45, 2.56, 2.67};//⽤来模拟512个⼈脸特征值.string id4 = "ddd";//⽤来模拟32位的uuid.std::vector<float> feature4{3.12, 3.23, 3.34, 3.45, 3.56, 3.67};//⽤来模拟512个⼈脸特征值.//先把⼈脸特征值的float数组转成json,然后保存到数据库中。
cjson的源码和例程在你⾃⼰的github上保存了cJSON *root1, *js_feature1;root1 = cJSON_CreateObject();cJSON_AddItemToObject(root1, "face_feature1", js_feature1 = cJSON_CreateArray());for(int i = 0; i < feature1.size(); i++){cJSON_AddItemToArray(js_feature1, cJSON_CreateNumber(feature1.at(i)));}char *s1 = cJSON_PrintUnformatted(root1);printf("s1:%s\n", s1);//先把⼈脸特征值的float数组转成json,然后保存到数据库中。
#VC++中链接数据库并实现(添加修改删除清空)功能
VC++中用ADO编程方法链接数据库并实现添加、修改、删除、清空等功能1、数据库为Microsoft Office Access 2003为例2、数据库名为DataBase.mdb,表名employees,添加编号、学号、姓名字段,类型为文本。
数据库放在p5根目录下。
3、建立新建项目MFCAppWizard[exe]名称为p5。
选择基本对话框。
然后添加控件,一个列表控件,三个编辑框,五个按钮。
如下在列表控件,右键属性。
设置如下:然后建立类向导,在MemberVariables视图中为3个编辑框和1个列表控件添加变量名称和类型如图:五个按钮的ID和名字改为:IDC_BUTADD,添加;IDC_BUTMOD,修改;IDC_BUTDEL,删除;IDC_BUTCLICK,清空;IDC_BUTTON1,退出。
4、为项目加类ADO类,在ClassView中视图中在p5classes上面点右键新建类,类的类型选GenericClass,名称为ADO,点确定。
同时在StdAfx.h头文件中加入ADO动态链接库,代码如下:#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace\rename("EOF","adoEOF">rename("BOF","adoBOF">//导入ADO动态链接库在ClassView视图中的CP5Dlg中加入自定义函数AddToGrid和OnButclear。
这两个函数是手动添加的。
5、在ADO.app中程序为// ADO.cpp: implementation of the ADO class.////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "p5.h"#include "ADO.h"#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__。