Sqlite 数据库的使用(demo)

Sqlite 数据库的创建

package com.example.wanglibo20171123;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SQlitepoen extends SQLiteOpenHelper{

    public SQlitepoen(Context context) {
        super(context, "user.db", null, 1);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(" create table user(id integer primary key autoincrement," +
                "goods_id varchar(100)," +
                "goods_name varchar(100)," +
                "goods_num varcahr(100)," +
                "goods_price double(7,2)," +
                "goods_total double(7,2)" +
                ")");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        
    }

}

Userdao 类的代码

package com.example.wanglibo20171123;
/**
 * dao 类
 */
import java.util.Currency;
import java.util.List;

import com.example.wanglibo20171123.user.datas.cart;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

public class goodsdao {
    private SQlitepoen sp;
    private SQLiteDatabase rd;
  public goodsdao(Context context){
      sp=new SQlitepoen(context);
      
  }
  //添加数据库
  public void add(List<cart> list){
      rd = sp.getReadableDatabase();
      for (int i = 0; i <list.size(); i++) {
//        cart c = new user().new datas().new cart();
        cart ca = list.get(i);
        String goods_id = ca.getGoods_id();
        String goods_name = ca.getGoods_name();
        String goods_num = ca.getGoods_num();
        String goods_price = ca.getGoods_price();
        String goods_total = ca.getGoods_total();
        rd.execSQL("insert into user(goods_id,goods_name,goods_num,goods_price,goods_total) values(?,?,?,?,?)",new String[]{goods_id,goods_name,goods_num,goods_price,goods_total});
    }
     rd.close();
  }
 
  //从数据库删除
  public void delete(String name){
      rd.execSQL("delete from user where goods_name=?",new String[]{name});
    //  rd.close();
  }
  //查询价格的
  public double select(Context context){
      double h=0;
      Cursor cursor = rd.rawQuery("select * from user", new String[]{});
      while(cursor!=null){
          double price = cursor.getDouble(cursor.getColumnIndex("goods_price"));
          Toast.makeText(context, price+"", 0).show();
          h+=price;
      }
    
    return h;
      
  }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 以下是一个使用 WinForms 程序操作 SQLite 数据库的示例源码: ```csharp using System; using System.Data.SQLite; using System.Windows.Forms; namespace SQLiteDemo { public partial class MainForm : Form { private SQLiteConnection connection; private SQLiteCommand command; public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { // 连接到 SQLite 数据库 connection = new SQLiteConnection("Data Source=database.db;Version=3;"); connection.Open(); command = new SQLiteCommand(connection); // 创建表格 command.CommandText = "CREATE TABLE IF NOT EXISTS Person (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INTEGER)"; command.ExecuteNonQuery(); } private void btnAdd_Click(object sender, EventArgs e) { // 插入数据 string name = tbName.Text; int age = Convert.ToInt32(tbAge.Text); command.CommandText = "INSERT INTO Person (Name, Age) VALUES (@name, @age)"; command.Parameters.AddWithValue("@name", name); command.Parameters.AddWithValue("@age", age); command.ExecuteNonQuery(); MessageBox.Show("数据已添加成功!"); } private void btnDisplay_Click(object sender, EventArgs e) { // 显示数据 command.CommandText = "SELECT * FROM Person"; using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int id = Convert.ToInt32(reader["Id"]); string name = reader["Name"].ToString(); int age = Convert.ToInt32(reader["Age"]); MessageBox.Show($"ID: {id}\nName: {name}\nAge: {age}"); } } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { // 关闭数据库连接 command.Dispose(); connection.Close(); } } } ``` 这个示例中,我们创建了一个名为 `MainForm` 的窗体,包含了用于输入名称和年龄的文本框,以及用于添加和显示数据的按钮。在窗体加载时,我们首先连接到 SQLite 数据库并创建了一个名为 `Person` 的表格。通过点击“添加”按钮,我们可以将输入的名称和年龄插入到数据库中。点击“显示”按钮,我们会从数据库中查询所有的数据,并在弹出消息框中显示出来。 ### 回答2: 下面是一个使用Winform程序操作SQLite数据库的示例代码: ```csharp using System; using System.Data.SQLite; using System.Windows.Forms; namespace WinformSQLiteDemo { public partial class MainForm : Form { private SQLiteConnection _conn; public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { // 创建数据库连接 _conn = new SQLiteConnection("Data Source=MyDatabase.db;Version=3;"); _conn.Open(); // 创建表 string createTableQuery = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INTEGER)"; SQLiteCommand createTableCmd = new SQLiteCommand(createTableQuery, _conn); createTableCmd.ExecuteNonQuery(); // 查询并显示数据 string selectQuery = "SELECT * FROM Users"; SQLiteCommand selectCmd = new SQLiteCommand(selectQuery, _conn); SQLiteDataReader reader = selectCmd.ExecuteReader(); while (reader.Read()) { string name = reader.GetString(1); int age = reader.GetInt32(2); dataGridView.Rows.Add(name, age); } // 关闭连接 reader.Close(); _conn.Close(); } private void addButton_Click(object sender, EventArgs e) { string name = nameTextBox.Text; int age = Convert.ToInt32(ageTextBox.Text); // 插入数据 _conn.Open(); string insertQuery = "INSERT INTO Users (Name, Age) VALUES (@name, @age)"; SQLiteCommand insertCmd = new SQLiteCommand(insertQuery, _conn); insertCmd.Parameters.AddWithValue("@name", name); insertCmd.Parameters.AddWithValue("@age", age); insertCmd.ExecuteNonQuery(); // 更新DataGridView dataGridView.Rows.Add(name, age); // 清除输入框 nameTextBox.Text = ""; ageTextBox.Text = ""; _conn.Close(); } } } ``` 这个示例代码包含一个主窗体(MainForm),它在加载时创建了一个SQLite数据库连接,并创建了一个名为"Users"的表。在加载时,它还从数据库中读取已有的用户数据,并将其显示在一个DataGridView控件中。 在窗体中还有一个添加按钮(addButton),当用户输入姓名和年龄后点击此按钮,程序将把数据插入到数据库中,并更新DataGridView以显示新添加的数据。 请注意,该示例中的数据库文件名为"MyDatabase.db",你可以根据需要修改它。 ### 回答3: 以下是一个用于操作SQLite数据库的WinForm程序的示例源代码: ```csharp using System; using System.Data; using System.Data.SQLite; using System.Windows.Forms; namespace SQLiteDemo { public partial class MainForm : Form { private SQLiteConnection connection; private SQLiteCommand command; public MainForm() { InitializeComponent(); } private void MainForm_Load(object sender, EventArgs e) { string connectionString = "Data Source=database.db;Version=3;"; connection = new SQLiteConnection(connectionString); command = new SQLiteCommand(connection); connection.Open(); CreateSampleTable(); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { connection.Close(); connection.Dispose(); } private void CreateSampleTable() { string createTableQuery = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INTEGER)"; command.CommandText = createTableQuery; command.ExecuteNonQuery(); } private void btnInsert_Click(object sender, EventArgs e) { string name = txtName.Text; int age = Convert.ToInt32(txtAge.Text); string insertQuery = $"INSERT INTO Users (Name, Age) VALUES ('{name}', {age})"; command.CommandText = insertQuery; command.ExecuteNonQuery(); MessageBox.Show("数据插入成功!"); LoadData(); } private void btnDelete_Click(object sender, EventArgs e) { int id = Convert.ToInt32(txtId.Text); string deleteQuery = $"DELETE FROM Users WHERE Id = {id}"; command.CommandText = deleteQuery; command.ExecuteNonQuery(); MessageBox.Show("数据删除成功!"); LoadData(); } private void btnUpdate_Click(object sender, EventArgs e) { int id = Convert.ToInt32(txtId.Text); string name = txtName.Text; int age = Convert.ToInt32(txtAge.Text); string updateQuery = $"UPDATE Users SET Name = '{name}', Age = {age} WHERE Id = {id}"; command.CommandText = updateQuery; command.ExecuteNonQuery(); MessageBox.Show("数据更新成功!"); LoadData(); } private void LoadData() { string selectQuery = "SELECT * FROM Users"; SQLiteDataAdapter adapter = new SQLiteDataAdapter(selectQuery, connection); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); dataGridView.DataSource = dataTable; } } } ``` 这个示例程序创建了一个包含三个字段(Id、Name和Age)的Users表。通过使用不同的按钮,可以插入、删除和更新数据库中的数据。每次操作完成后,数据表将被重新加载到DataGridView控件中以显示更新后的内容。请确保已在程序所在的目录下创建了一个名为database.db的SQLite数据库文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jonly_W

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值