Method for C to operate read write database of SQLite database

  • 2021-11-01 04:19:53
  • OfStack

This article illustrates how C # operates the SQLite database to read and write the database. Share it for your reference, as follows:

Here's a demonstration of reading and writing a database and displaying its data in a form (Form):


Database(SQLite) - > DataAdapter - > DataSet - > DataGridView


Database(SQLite) < - DataAdapter < - DataSet < - DataGridView

1. Assume that the existing database table student has the following fields:








2. DataGrideView controls and DataSet controls

Drag and drop an DataGrideView control on Form (note: you do not need to specify a data source (DataSource), but only need to value the DataSource member of the DataGridView object in your code); Then drag and drop an DataSet control (this control does not appear on the form).

3. Read and display in DataGrideView

mDbConn = new SQLiteConnection("Data Source=sqlite.student.db");
dataAdapter = new SQLiteDataAdapter("SELECT * FROM student;", mDbConn);// Read database 
dataAdapter.FillSchema(dataSet1, SchemaType.Source, "student");// Set the database table student (in this case, the primary key constraint) is populated with the schema information of the dataSet1 Adj. student In the table 
dataAdapter.Fill(dataSet1 ,  "student");// Padding DataSet Control 
dataGridView1.DataSource = dataSet1.Tables["Table"];// Attention, DataSet The data tables in the Table, Table1, Table2...


dataAdapter.FillSchema(dataSet1, SchemaType.Source, "student");
Fill the schema information of the database table student (in this case the primary key constraint) into the student table of dataSet1

4. Write and update DataGrideView

DataRow dataRow = dataSet1.Tables["student"].NewRow();
dataRow["number"] = "20120010";
dataRow["name"] = " Li 4";
dataRow["grade"] = "2";
dataGridView1.Invalidate();// Real-time update dataGridView1
dataAdapter.InsertCommand = new SQLiteCommand("INSERT INTO student(number, name, grade) VALUES('" + dataRow["number"] + "','" + dataRow["name"] + "','" + dataRow["grade"] + "')", mDbConn);
dataAdapter.Update(dataSet1, "student"");

Parameter literature

For more readers interested in C # related content, please check the topics on this site: "Summary of thread usage skills in C # programming", "Summary of Excel # operating skills", "Summary of XML file operation skills in C #", "C # common control usage tutorial", "WinForm control usage summary", "C # data structure and algorithm tutorial", "C # array operation skills summary" and "C # object-oriented programming introduction tutorial"

I hope this article is helpful to everyone's C # programming.

Related articles: