【转】C# 对sqlite基本操作,带批量插入

原文地址:https://download.csdn.net/download/mic_gary/10154869

public class SQLiteHelper
    {
        //数据库连接字符串
        public static string connectionString;

        public SQLiteHelper() { }

        #region 公用方法

        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }

        public static bool Exists(string strSql)
        {
            object obj = GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public static bool Exists(string strSql, params SQLiteParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SQLite.SQLiteException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行SQL语句,设置命令的执行等待时间
        /// </summary>
        /// <param name="SQLString"></param>
        /// <param name="Times"></param>
        /// <returns></returns>
        public static int ExecuteSqlByTime(string SQLString, int Times)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SQLite.SQLiteException E)
                    {
                        connection.Close();
                        throw new Exception(E.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>
        public static void ExecuteSqlTran(ArrayList SQLStringList)
        {
            using (SQLiteConnection conn = new SQLiteConnection(connectionString))
            {
                conn.Open();
                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = conn;
                SQLiteTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n].ToString();
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    tx.Rollback();
                    throw new Exception(E.Message);
                }
            }
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, string content)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand(SQLString, connection);
                SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static object ExecuteSqlGet(string SQLString, string content)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand(SQLString, connection);
                SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
                SQLiteParameter myParameter = new SQLiteParameter("@fs", DbType.Binary);
                myParameter.Value = fs;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SQLite.SQLiteException E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SQLite.SQLiteException e)
                    {
                        connection.Close();
                        throw new Exception(e.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回SQLiteDataReader(使用该方法切记要手工关闭SQLiteDataReader和连接)
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SQLiteDataReader</returns>
        public static SQLiteDataReader ExecuteReader(string strSQL)
        {
            SQLiteConnection connection = new SQLiteConnection(connectionString);
            SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
            try
            {
                connection.Open();
                SQLiteDataReader myReader = cmd.ExecuteReader();
                return myReader;
            }
            catch (System.Data.SQLite.SQLiteException e)
            {
                throw new Exception(e.Message);
            }
            //finally //不能在此关闭,否则,返回的对象将无法使用
            //{
            //    cmd.Dispose();
            //    connection.Close();
            //}
        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        public static DataSet Query(string SQLString, string TableName)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.Fill(ds, TableName);
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        /// <summary>
        /// 执行查询语句,返回DataSet,设置命令的执行等待时间
        /// </summary>
        /// <param name="SQLString"></param>
        /// <param name="Times"></param>
        /// <returns></returns>
        public static DataSet Query(string SQLString, int Times)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.SelectCommand.CommandTimeout = Times;
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SQLite.SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, params SQLiteParameter[] cmdParms)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.SQLite.SQLiteException E)
                    {
                        throw new Exception(E.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SQLiteParameter[])</param>
        public static bool ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (SQLiteConnection conn = new SQLiteConnection(connectionString))
            {

                conn.Open();
                SQLiteTransaction trans=null;

                    SQLiteCommand cmd = new SQLiteCommand();
                    try
                    {
                        int num = 1;
                        //循环
                        trans = conn.BeginTransaction();
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {

                            string cmdText = myDE.Key.ToString();
                            SQLiteParameter[] cmdParms = (SQLiteParameter[])myDE.Value;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                            num++;
                        }
                        trans.Commit();
                        return true;
                    }
                    catch(Exception ex)
                    {
                        //trans.Rollback();
                        string a = ex.ToString();
                        //throw;

                        return false;
                    }

            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句,返回查询结果(object)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果(object)</returns>
        public static object GetSingle(string SQLString, params SQLiteParameter[] cmdParms)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SQLite.SQLiteException e)
                    {
                        throw new Exception(e.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句,返回SQLiteDataReader (使用该方法切记要手工关闭SQLiteDataReader和连接)
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SQLiteDataReader</returns>
        public static SQLiteDataReader ExecuteReader(string SQLString, params SQLiteParameter[] cmdParms)
        {
            SQLiteConnection connection = new SQLiteConnection(connectionString);
            SQLiteCommand cmd = new SQLiteCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                SQLiteDataReader myReader = cmd.ExecuteReader();
                cmd.Parameters.Clear();
                cmd.Dispose();
                connection.Close();
                return myReader;
            }
            catch (System.Data.SQLite.SQLiteException e)
            {
                throw new Exception(e.Message);
            }
            //finally //不能在此关闭,否则,返回的对象将无法使用
            //{
            //    cmd.Dispose();
            //    connection.Close();
            //}    

        }

        /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, params SQLiteParameter[] cmdParms)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                SQLiteCommand cmd = new SQLiteCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SQLite.SQLiteException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }

        public static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {

                foreach (SQLiteParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion

        #region 参数转换
        /// <summary>
        /// 放回一个SQLiteParameter
        /// </summary>
        /// <param name="name">参数名字</param>
        /// <param name="type">参数类型</param>
        /// <param name="size">参数大小</param>
        /// <param name="value">参数值</param>
        /// <returns>SQLiteParameter的值</returns>
        public static SQLiteParameter MakeSQLiteParameter(string name, DbType type, int size, object value)
        {
            SQLiteParameter parm = new SQLiteParameter(name, type, size);
            parm.Value = value;
            return parm;
        }

        public static SQLiteParameter MakeSQLiteParameter(string name, DbType type, object value)
        {
            SQLiteParameter parm = new SQLiteParameter(name, type);
            parm.Value = value;
            return parm;
        }

        #endregion
    }

ublic partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SQLiteHelper.connectionString = "Data Source=" + Application.StartupPath + @"\InfoDataBase.db3;BinaryGUID=False";
            //button4_Click(null, null);
        }

        private void AddRows(List<StudentClass> stuList)
        {
            dataGridView1.Rows.Clear();
            for (int i = 0; i < stuList.Count; i++)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(dataGridView1);
                row.Cells[0].Value = stuList[i].Number.ToString();
                row.Cells[1].Value = stuList[i].Name.ToString();
                row.Cells[2].Value = stuList[i].Sex.ToString();
                row.Cells[3].Value = stuList[i].Address.ToString();
                dataGridView1.Rows.Add(row);
            }
        }

        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            AddRows(LoadInfo());
        }

        private List<StudentClass> LoadInfo()
        {
            List<StudentClass> list = new List<StudentClass>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"select stuID,stuName,stuSex,stuAddress from studentInfo order by stuID ASC");
            foreach (System.Data.DataTable table in SQLiteHelper.Query(strSql.ToString()).Tables)
            {
                foreach (DataRow row in table.Rows)
                {
                    StudentClass stu = new StudentClass();
                    stu.Number = int.Parse(row[0].ToString());
                    stu.Name = row[1].ToString();
                    stu.Sex = row[2].ToString();
                    stu.Address = row[3].ToString();
                    list.Add(stu);
                }
                break;
            }
            return list;
        }

        /// <summary>
        /// 增加一条记录按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)
                || string.IsNullOrEmpty(textBox3.Text) || string.IsNullOrEmpty(textBox4.Text))
            {
                MessageBox.Show("不能为空");
                return;
            }

                StudentClass stu = new StudentClass();
                stu.Number = int.Parse(textBox1.Text);
                stu.Name = (textBox2.Text);
                stu.Sex = (textBox3.Text);
                stu.Address = (textBox4.Text);
                if (!InsertInfo(stu))
                    MessageBox.Show("插入记录失败");
                else
                    button4_Click(null,null);
        }

        /// <summary>
        /// 插入一条记录
        /// </summary>
        /// <param name="stu">一个学生的实例</param>
        /// <returns>true为成功</returns>
        private bool InsertInfo(StudentClass stu)
        {
            Hashtable ht = new Hashtable();

            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into studentInfo(");
            strSql.Append("stuID,stuName,stuSex,stuAddress)");
            strSql.Append(" values (");
            strSql.Append("@id,@name,@sex,@address)");
            SQLiteParameter[] parameters = {
                    SQLiteHelper.MakeSQLiteParameter("@id", DbType.Int32,stu.Number),
                    SQLiteHelper.MakeSQLiteParameter("@name", DbType.String,128,stu.Name),
                    SQLiteHelper.MakeSQLiteParameter("@sex", DbType.String,stu.Sex),
                    SQLiteHelper.MakeSQLiteParameter("@address",DbType.String,stu.Address),
                    };

            ht.Add(strSql, parameters);

            return SQLiteHelper.ExecuteSqlTran(ht);

        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count != 0)
            {
                int number = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
                if (delete(number) < 1)
                    MessageBox.Show("删除失败");
                else
                    button4_Click(null, null);
            }
        }
        /// <summary>
        /// 删除一条记录
        /// </summary>
        /// <param name="stuID">数据库学生表的主键,唯一</param>
        /// <returns>删除的记录条数,等于0为删除失败</returns>
        private int delete(int stuID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from studentInfo where stuID=‘");
            strSql.Append(stuID);
            strSql.Append("‘");

            return SQLiteHelper.ExecuteSql(strSql.ToString());
        }

        /// <summary>
        /// 修改一条记录,也就是更新一条记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)
                 || string.IsNullOrEmpty(textBox3.Text) || string.IsNullOrEmpty(textBox4.Text))
            {
                MessageBox.Show("不能为空");
                return;
            }
            StudentClass stu = new StudentClass();
            stu.Number = int.Parse(textBox1.Text);
            stu.Name = (textBox2.Text);
            stu.Sex = (textBox3.Text);
            stu.Address = (textBox4.Text);
            if (update(stu) < 1)
                MessageBox.Show("更新记录失败");
            else
                button4_Click(null, null);
        }

        private int update(StudentClass stu)
        {
            StringBuilder strSql = new StringBuilder();
            //UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
            strSql.Append(@"update studentInfo set stuName=‘" + stu.Name + "‘,stuSex=‘" + stu.Sex +
                "‘, stuAddress=‘" + stu.Address + "‘ where stuID=" + stu.Number);
            return SQLiteHelper.ExecuteSql(strSql.ToString());
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.SelectedRows.Count != 0)
            {
                try
                {
                    textBox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                    textBox2.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
                    textBox3.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
                    textBox4.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
                }
                catch { }
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //StringBuilder sb = new StringBuilder();
            //for (int i = 20000; i < 30000; i++)
            //{
            //    sb.Append("insert into studentInfo values(‘女‘,‘马渼凯‘,‘凯迪" + i + "‘," + i+");");
            //}
            //SQLiteHelper.ExecuteSql(sb.ToString());
            InserPatch();

        }

        private void InserPatch()
        {
            using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + Application.StartupPath + @"\InfoDataBase.db3;BinaryGUID=False"))
            {

                using (SQLiteCommand insertRngCmd = (SQLiteCommand)conn.CreateCommand())
                {
                    insertRngCmd.CommandText = @"INSERT INTO studentInfo VALUES (@sex, @adr, @name, @id)";
                    conn.Open();
                    var transaction = conn.BeginTransaction();

                    for (int s = 10; s < 1000000; s++)
                    {
                        insertRngCmd.Parameters.AddWithValue("@sex", "male");
                        insertRngCmd.Parameters.AddWithValue("@adr", "clanbian");
                        insertRngCmd.Parameters.AddWithValue("@name", "Great" + s);
                        insertRngCmd.Parameters.AddWithValue("@id", s);

                        insertRngCmd.ExecuteNonQuery();
                    }
                    transaction.Commit();
                }
            }
        }
    }

调用例子

原文地址:https://www.cnblogs.com/ZXdeveloper/p/10893420.html

时间: 2024-10-15 08:57:20

【转】C# 对sqlite基本操作,带批量插入的相关文章

启用事务操作,解决批量插入或更新sqlite,mssql等数据库耗时问题

private void button1_Click(object sender, EventArgs e) { //Sqlite使用事务批量操作 极大的提高速度 DateTime starttime = DateTime.Now; using (SQLiteConnection con = new SQLiteConnection(connStr)) { con.Open(); DbTransaction trans = con.BeginTransaction();//开始事务 SQLite

Android批量插入数据到SQLite数据库

Android中在sqlite插入数据的时候默认一条语句就是一个事务,因此如果存在上万条数据插入的话,那就需要执行上万次插入操作,操作速度可想而知.因此在Android中插入数据时,使用批量插入的方式可以大大提高插入速度. 有时需要把一些数据内置到应用中,常用的有以下2种方式:其一直接拷贝制作好的SQLite数据库文件,其二是使用系统提供的数据库,然后把数据批量插入.我更倾向于使用第二种方式:使用系统创建的数据库,然后批量插入数据.批量插入数据也有很多方法,那么那种方法更快呢,下面通过一个dem

Qt SQLite 批量插入优化(SQLite默认将每条语句看成单独的事务)good

使用SQLite存储数据时发现插入速度太慢,程序跑了将近五分钟才插入了不到三千条.上网查资料才发现,SQLite这种文件数据库与MySql机制不一样,每条事务都有打开和关闭文件的步骤,SQLite默认将每条语句看成单独的事务.当我逐条插入数据时,就会出现大量的文件IO操作,效率自然不高.需要将多个插入操作放到一个事务中,就可以显著提升插入效率. QT中使用事务的方法如下: QSqlDatabase app_database;// 设置数据库参数// ...app_database.transac

android SQLite 批量插入数据慢的解决方案 (针对于不同的android api 版本)

原地址 :http://www.cnblogs.com/wangmars/p/3914090.html SQLite,是一款轻型的数据库,被广泛的运用到很多嵌入式的产品中,因为占用的资源非常少,二其中的操作方式几乎和我们接触的数据库不多,甚至只有几百K的他自然会被需求者青睐,下面讲一下在这样的轻型数据库中怎么对他进行一些读写操作. 之前做选择联系人的时候出现如果一个手机里联系人超过2000的话,往数据库里面插入会非常耗时,不同的手机存储的条数不同,这个存储的数量和手机的内存有很大的关系,往往取决

Android 批量插入数据到SQLite数据库

Android中在sqlite插入数据的时候默认一条语句就是一个事务,因此如果存在上万条数据插入的话,那就需要执行上万次插入操作,操作速度可想而知.因此在Android中插入数据时,使用批量插入的方式可以大大提高插入速度. 有时需要把一些数据内置到应用中,常用的有以下2种方式:其一直接拷贝制作好的SQLite数据库文件,其二是使用系统提供的数据库,然后把数据批量插入.我更倾向于使用第二种方式:使用系统创建的数据库,然后批量插入数据.批量插入数据也有很多方法,那么那种方法更快呢,下面通过一个dem

android SQLite 批量插入数据慢的解决方案 (正对于不同的android api 版本)

SQLite,是一款轻型的数据库,被广泛的运用到很多嵌入式的产品中,因为占用的资源非常少,二其中的操作方式几乎和我们接触的数据库不多,甚至只有几百K的他自然会被需求者青睐,下面讲一下在这样的轻型数据库中怎么对他进行一些读写操作. 之前做选择联系人的时候出现如果一个手机里联系人超过2000的话,往数据库里面插入会非常耗时,不同的手机存储的条数不同,这个存储的数量和手机的内存有很大的关系,往往取决于手机内存,下面对于数据量大的情况来写一下sqlite的批量查询. SqLite 掺入数据有几种 第一种

mysql三种带事务批量插入

前言 对于像我这样的业务程序员开发一些表单内容是家常便饭的事情,说道表单 我们都避免不了多行内容的提交,多行内容保存,自然要用到数据库,如果循环打扰我数据库,数据库也会觉得很累,从而增加数据库服务器压力.所以小子不才,根据平时经验总结了一下用到的批量插入的方法代码.本文是针对c#语言开发,数据库是mysql数据库.当然我这是单片机的本地电脑运行,跟服务器上有很大区别,到了服务器上可能跑的比这快的多,话不多说看下文. 一 生成数据 简而言之吧,就拿五万数据实验吧,这里面我就收集了五万条数据 二 批

sqlhelper(带sqlbulkcopy批量插入)

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.SqlClient; namespace DataController{    static class SqlHelper    {        const int SQLTimeout = 120;        const string Connectio

Mybatis 批量插入带oracle序列例子+ORA-02287: 此处不允许序号

在使用mybatis进行批量插入时,发现对于使用Oracle的自动增长序列时提示 : ORA-02287: 此处不允许序号 的错误,下面的这种使用可以解决问题: <!-- 批量插入 --> <insert id="inserts" parameterType="java.util.List">       insert into PRESON        select SEQ_PRESON_ID.NEXTVAL,A.* from(