Esempio n. 1
0
        //Set up the connection with the password
        public static SQLiteConnection Connection(string dbname, string pwd)
        {
            string datasource = dbname;
            SQLiteConnection.CreateFile(datasource);
            //连接数据库
            SQLiteConnection connection = new SQLiteConnection();
            SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
            connstr.DataSource = datasource;
            connstr.Password = pwd;//设置密码,SQLite ADO.NET实现了数据库密码保护

            //将连接的信息传递给connection
            connection.ConnectionString = connstr.ToString();

            if (connection == null)
            {
                connection = new SQLiteConnection();
                connection.ConnectionString = connstr.ToString();
                connection.Open();
            }
            else if (connection.State == System.Data.ConnectionState.Closed)
            {
                connection.Open();
            }
            else if (connection.State == System.Data.ConnectionState.Broken)
            {
                connection.Close();
                connection.Open();
            }

            return connection;
        }
 public CardRefundPayService()
 {
     string localDriver = "C";
     if (Directory.Exists("D:\\"))
     {
         localDriver = "D";
     }
     string dbPath = localDriver + ":\\DataBase\\top4pos.db3";
     if (!File.Exists(dbPath))
     {
         //创建数据库
         SQLiteConnection.CreateFile(dbPath);
     }
     SQLiteConnectionStringBuilder connectionString = new SQLiteConnectionStringBuilder
                                                         {
                                                             DataSource = dbPath,
                                                             Password = "******",
                                                             Pooling = true,
                                                             FailIfMissing = false
                                                         };
     m_SQLiteHelper = new SQLiteHelper(connectionString.ToString());
     //判断表是否存在
     string strSql = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='CardRefundPay'";
     if (!m_SQLiteHelper.Exists(strSql))
     {
         string createTableSql = @"create table CardRefundPay(StoreValueID INTEGER primary key autoincrement, 
                                                         CardNo varchar(50), ShopID varchar(36), 
                                                         TradePayNo varchar(30), 
                                                         PayAmount decimal(12, 4), EmployeeNo varchar(20), 
                                                         DeviceNo varchar(16), IsFixed Integer,
                                                         CreateTime datetime, LastTime datetime);";
         m_SQLiteHelper.ExecuteSql(createTableSql);
     }
 }
Esempio n. 3
0
 public void TestQuery()
 {
     var builder = new SQLiteConnectionStringBuilder();
       builder.DataSource = "test.db";
       using (DbConnection connection = new SQLiteConnection(builder.ToString()))
       {
     connection.Open();
     using (var cmd1 = connection.CreateCommand())
     {
       cmd1.CommandText = @"SELECT name FROM sqlite_master WHERE type='table' AND name='table_test';";
       var reader = cmd1.ExecuteReader();
       if (reader.Read())
       {
     var tableName = reader.GetString(0);
     System.Diagnostics.Trace.WriteLine(String.Format("table name={0}", tableName));
       }
       else
       {
     using (var cmd2 = connection.CreateCommand())
     {
       cmd2.CommandText = @"Create Table 'table_test' (num Integer, str)";
       cmd2.ExecuteNonQuery();
     }
       }
     }
       }
 }
Esempio n. 4
0
        public static void UpdataObjectById <T>(T newInstance) where T : BaseObject
        {
            SQLiteTransaction transaction = null;
            string            tableName   = typeof(T).Name;

            try
            {
                if (commonConnection == null)
                {
                    commonConnection = new SQLiteConnection();
                    SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
                    connstr.DataSource = DbFileName;
                    commonConnection.ConnectionString = connstr.ToString();
                }
                commonConnection.Open();
                transaction = commonConnection.BeginTransaction();
                SQLiteCommand cmd = new SQLiteCommand(commonConnection);
                cmd.Transaction = transaction;
                cmd.CommandText = "Delete  from " + tableName + " where id='" + newInstance.Id.ToString() + "'";;
                cmd.ExecuteNonQuery();
                cmd.CommandText = BuildInsertCommand(tableName, newInstance);;
                cmd.ExecuteNonQuery();
                transaction.Commit();
                commonConnection.Close();
            }
            catch (Exception e)
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }
                commonConnection.Close();
                throw e;
            }
        }
Esempio n. 5
0
    public bool Connect()
    {
        Debug.Log("DataBase connect: " + Predefine.DatabaseName);

        //Debug.Log("sqlite3 version: " + SQLite3.LibVersionNumber());
        if (_connection != null)
        {
            Debug.Log("dataBase has connected, needn't connect again");
            return(true);
        }
#if !RUNINSERVER
        var dbPath = "";
        Debug.Log("DataBase file path: " + dbPath);
        _connection = new SQLiteConnection(Key, dbPath, SQLiteOpenFlags.ReadOnly);
#else
#if DEBUG
        var dbPath = "D:/Work/Unity/Project/Client/p25/Assets/StreamingAssets/cfg";
#else
        var dbPath = "./cfg";
#endif
        Debug.Log("DataBase file path: " + dbPath);
        _connection = new System.Data.SQLite.SQLiteConnection();
        System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
        connstr.DataSource = dbPath;
        //connstr.
        _connection.ConnectionString = connstr.ToString();
        _connection.Open();
#endif
        return(true);
    }
Esempio n. 6
0
        public static T GetObject <T>(string key, object value) where T : BaseObject
        {
            T      obj       = Activator.CreateInstance <T>();
            string tableName = obj.GetType().Name;//.Substring(obj.GetType().Name.LastIndexOf('.'));

            if (commonConnection == null)
            {
                commonConnection = new SQLiteConnection();
                SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
                connstr.DataSource = DbFileName;
                commonConnection.ConnectionString = connstr.ToString();
            }
            try
            {
                commonConnection.Open();
                SQLiteCommand cmd = new SQLiteCommand(commonConnection);
                cmd.CommandText = "Select * from " + tableName + " where " + key + "='" + value.ToString() + "'";
                SQLiteDataReader sdr = cmd.ExecuteReader();
                while (sdr.Read())
                {
                    obj.SetProperties(sdr);
                }
                commonConnection.Close();
            }
            catch//(Exception ex)
            {
                commonConnection.Close();
                return(null);
            }
            return(obj);
        }
Esempio n. 7
0
 public DBManager(String dataSource)
 {
     // build connection string
     SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
     builder.DataSource = dataSource;
     connectionString = builder.ToString();
 }
Esempio n. 8
0
        public static List <T> GetAllObject <T>() where T : BaseObject
        {
            List <T> list      = new List <T>();
            string   tableName = typeof(T).Name;//.Substring(typeof(T).Name.LastIndexOf('.'));

            if (commonConnection == null)
            {
                commonConnection = new SQLiteConnection();
                SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
                connstr.DataSource = DbFileName;
                commonConnection.ConnectionString = connstr.ToString();
            }
            try
            {
                commonConnection.Open();
                SQLiteCommand cmd = new SQLiteCommand(commonConnection);
                cmd.CommandText = "Select * from " + tableName + "";
                SQLiteDataReader sdr = cmd.ExecuteReader();
                while (sdr.Read())
                {
                    T obj = Activator.CreateInstance <T>();
                    obj.SetProperties(sdr);
                    list.Add(obj);
                }
                commonConnection.Close();
            }
            catch (Exception e)
            {
                commonConnection.Close();
                throw e;
            }
            return(list);
        }
Esempio n. 9
0
        /// <summary>
        /// Constructor for talking to a SQLite database.
        /// </summary>
        /// <param name="databasePath">Path to the db file.</param>
        public SQLiteDescriptor(string databasePath)
        {
            if (!StringHelper.IsNonBlank(databasePath))
            {
                throw new ArgumentNullException("databasePath", "Database file path cannot be null/blank.");
            }
            SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
            builder.DataSource = _databasePath = databasePath;

            // we want to disable pooling so we don't wind up locking
            // the file indefinitely.
            builder.Pooling = false;
            _usePooling = false;
            // There is no password, so the strings are the same.
            _cleanConnStr = builder.ToString();
            _connectionStr = builder.ToString();
        }
Esempio n. 10
0
 /// <summary>
 /// 获得连接数据库
 /// </summary>
 /// <param name="datasource"></param>
 /// <returns></returns>
 public SQLiteConnection getSqlLiteDB(String datasource)
 {
     SQLiteConnection conn = new SQLiteConnection();
     SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
     connstr.DataSource = "databases/" + datasource + ".db";
     conn.ConnectionString = connstr.ToString();
     return conn;
 }
Esempio n. 11
0
 private BookDataBase()
 {
     conn = new SQLiteConnection();
     connstr = new SQLiteConnectionStringBuilder();
     cmd = new SQLiteCommand();
     connstr.DataSource = dbName;
     conn.ConnectionString = connstr.ToString();
     conn.Open();
 }
Esempio n. 12
0
        public Storage()
        {
            string datasource = "map.db";

            if (!System.IO.File.Exists(datasource))
                SQLiteConnection.CreateFile(datasource);

            conn = new SQLiteConnection();
            conStr = new SQLiteConnectionStringBuilder();

            conStr.DataSource = datasource;

            conn.ConnectionString = conStr.ToString();

            // open connection;
            conn.Open();

            SQLiteCommand cmd = new SQLiteCommand();
            string sql = string.Empty;
            cmd.Connection = conn;

            sql = "drop table if exists label;";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();

            sql = "drop table if exists path;";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();

            sql = "drop table if exists quadtree;";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();

            sql = "create table label (id INTEGER, data BLOB);";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();

            sql = "create table path (id INTEGER, data BLOB);";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();

            sql = "create table quadtree (quadkey TEXT, data BLOB);";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();

            sql = "create index label_id ON label(id);";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();

            sql = "create index path_id ON path(id);";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();

            sql = "create index quadtree_quadkey ON quadtree (quadkey);";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
        }
		public DbTestSqlLiteAdo()
		{
			SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder {DataSource = PathToDb};
			pConnectionString = builder.ToString();
			Random r = new Random();
			pRandomString = r.NextDouble().ToString();
			bool ok = SetDllDirectory(PathToDll);
			Debug.Assert(ok);
		}
Esempio n. 14
0
 public SQLiteOperate()
 {
     // 初始化
     DataSource            = @".\CashBookData.db"; // 数据库文件名
     connString.DataSource = DataSource;
     Password              = "******";   // 数据库密码
     connString.Password   = Password;
     conn.ConnectionString = connString.ToString();
 }
Esempio n. 15
0
 public static void SqlServerToSqlLite(string db, string sql)
 {
     //string sql = "select  [gzDay],[gzMonth],[gzYear],DateValue=rtrim([DateValue])+' '+ substring(JieQi,4,5),[weekDay],[constellation],JieQi,[nlMonth],[nlDay]  from [ChineseTenThousandCalendar] where left(ltrim(JieQi),2) in (" + JieQiHelper.GetInJieQis() + ")";
     System.Data.SqlClient.SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection();
     sqlCon.ConnectionString = "server=(local);user id=sa;password=***;initial catalog=HanZiMisc;TimeOut=10000;Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1";
     System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(sql);
     sqlCmd.Connection = sqlCon;
     sqlCon.Open();
     System.Data.SqlClient.SqlDataReader sqlReader = sqlCmd.ExecuteReader();
     if (sqlReader != null)
     {
         string datasource = db;// Application.StartupPath + "/JieQi.db";
         System.Data.SQLite.SQLiteConnection.CreateFile(datasource);
         //连接数据库
         System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection();
         System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
         connstr.DataSource    = datasource;
         connstr.Password      = "******";//可以设密码
         conn.ConnectionString = connstr.ToString();
         conn.Open();
         //conn.ChangePassword("nguchen");//可以改已打开CON的密码
         //创建表
         System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
         string sqlc = "CREATE TABLE ChinaJiQiTable(ID Integer PRIMARY KEY,DayGZ TEXT(4) NULL,MonthGZ TEXT(4) NULL,YearGZ TEXT(4) NULL,	DateValue datetime NULL,Week TEXT(6) NULL,Star TEXT(6) NULL,	JieQi TEXT(30) NULL,	NongLiMonth TEXT(6) NULL,NongLiDay TEXT(4) NULL)";
         cmd.CommandText = sqlc;
         cmd.Connection  = conn;
         cmd.ExecuteNonQuery();
         //插入数据
         SQLiteParameter[] sqlparams = new SQLiteParameter[]
         {
             new SQLiteParameter("@ID", DbType.Int64, 10),
             new SQLiteParameter("@dG", DbType.String, 4),
             new SQLiteParameter("@mG", DbType.String, 4),
             new SQLiteParameter("@yG", DbType.String, 4),
             new SQLiteParameter("@start", DbType.String, 6),
             new SQLiteParameter("@wk", DbType.String, 6),
             new SQLiteParameter("@date", DbType.DateTime),
             new SQLiteParameter("@jieqi", DbType.String, 30),
             new SQLiteParameter("@nM", DbType.String, 6),
             new SQLiteParameter("@nD", DbType.String, 6),
         };
         cmd.Parameters.AddRange(sqlparams);
         while (sqlReader.Read())
         {
             InsertSQLiteGZTable(sqlReader["DateValue"].ToString().Trim(), sqlReader["weekDay"].ToString().Trim(), sqlReader["constellation"].ToString().Trim(),
                                 sqlReader["gzYear"].ToString().Trim(), sqlReader["gzMonth"].ToString().Trim(), sqlReader["gzDay"].ToString().Trim(), sqlReader["JieQi"].ToString().Trim(),
                                 sqlReader["nlMonth"].ToString().Trim(), sqlReader["nlDay"].ToString().Trim(), conn, cmd);
         }
         sqlReader.Close();
         conn.Close();
         cmd.Dispose();
     }
     sqlCon.Close();
     sqlCmd = null;
     sqlCon.Dispose();
 }
Esempio n. 16
0
        public LemmaDatabase(string fileName)
        {
            SQLiteConnectionStringBuilder connBuilder = new SQLiteConnectionStringBuilder();
            connBuilder.DataSource = fileName;
            connBuilder.Version = 3;

            conn = new SQLiteConnection(connBuilder.ToString());
            conn.Open();
            InitializeDatabase();
        }
Esempio n. 17
0
        private DBHandler()
        {
            this.connection = new SQLiteConnection();
            string datasource = ConfigurationManager.AppSettings["DataSource"].ToString();
            SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
            connstr.DataSource = datasource;
            this.connection.ConnectionString = connstr.ToString();
            this.connection.Open();

            this.dataContext = new StudentDataContext(this.connection);
        }
Esempio n. 18
0
        //Initialize values
        private void Initialize(string db_name, string db_password)
        {
            connectionString = new SQLiteConnectionStringBuilder();
            connectionString.DataSource = db_name;
            connectionString.Version = 3;

            if(!String.IsNullOrEmpty(db_password))
                connectionString.Password = db_password;

            connection = new SQLiteConnection(connectionString.ToString());
        }
Esempio n. 19
0
 static SQLite()
 {
     //var constring = $@"Data Source={_dbPath};Version=3;";
     var constring = new SQLiteConnectionStringBuilder
     {
         DataSource = _dbPath,
         Version = 3,
     };
     Connection = new SQLiteConnection(constring.ToString()) {ParseViaFramework = true};
     //
 }
Esempio n. 20
0
        /// <summary>
        /// Initializes a new instance of the SQLiteUrlTokenStore class.
        /// </summary>
        /// <param name="connectionString">The connection string to use when connecting to the database.</param>
        public SQLiteUrlTokenStore(string connectionString)
        {
            this.ConnectionString = connectionString;
            this.EnsureConnectionString();

            SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder(this.ConnectionString);
            builder.DataSource = ResolveDatabasePath(builder.DataSource);
            this.ConnectionString = builder.ToString();

            EnsureDatabase(builder.DataSource);
        }
Esempio n. 21
0
        public string GetConnection()
        {
            var d = new System.Data.SQLite.SQLiteConnectionStringBuilder()
            {
                DataSource = DB_NAME
            };

            d.Add("mode", "memory");
            d.Add("cache", "shared");
            return(d.ToString());
        }
Esempio n. 22
0
 public ImageCache(string filename)
 {
     var builder = new SQLiteConnectionStringBuilder
     {
         BinaryGUID = true,
         DataSource = filename,
         Version = 3
     };
     string connectionString = builder.ToString();
     m_sqlCon = new SQLiteConnection(connectionString);
     m_sqlCon.Open();
 }
Esempio n. 23
0
 public SQLiteAdapter(string dbPath)
 {
     try {
         SQLiteConnectionStringBuilder connBuilder = new SQLiteConnectionStringBuilder();
         connBuilder.DataSource = dbPath;
         connBuilder.Version = 3;
         connBuilder.JournalMode = SQLiteJournalModeEnum.Wal;
         this.conn = new SQLiteConnection(connBuilder.ToString());
         this.conn.Open();
     } catch (Exception e) {
         throw e;
     }
 }
Esempio n. 24
0
        public static string ConnectionStringExample()
        {
            var b = new System.Data.SQLite.SQLiteConnectionStringBuilder(@"Data Source=e:\\StorageDB\\StorageDB.sqlite");

            b.CacheSize         = 8192;
            b.JournalMode       = System.Data.SQLite.SQLiteJournalModeEnum.Wal;
            b.ForeignKeys       = true;
            b.RecursiveTriggers = true;
            b.Enlist            = true;
            b.SyncMode          = System.Data.SQLite.SynchronizationModes.Normal;
            b.ReadOnly          = true;
            b.Pooling           = true;
            return(b.ToString());
        }
Esempio n. 25
0
        public static string GetConnectString(string sqliteDataSource)
        {
            var builder = new System.Data.SQLite.SQLiteConnectionStringBuilder {
                DataSource   = sqliteDataSource,
                Version      = 3,
                LegacyFormat = false,
                //PageSize = 8192,
                //CacheSize = 81920,
                SyncMode    = SynchronizationModes.Full, //途中で強制的に電源をOFFにすることも考えられるため。
                JournalMode = SQLiteJournalModeEnum.Default
            };

            return(builder.ToString());
        }
Esempio n. 26
0
        public static string GetSimpleConnString(string input)
        {
            var cb = new SQLiteConnectionStringBuilder(input)
            {
                ReadOnly = false,
                ForeignKeys = false,
                SyncMode = SynchronizationModes.Full,
                //JournalMode = SQLiteJournalModeEnum.Wal,
                FailIfMissing = false,
                BinaryGUID = false,
            };

            return cb.ToString();
        }
Esempio n. 27
0
 /// <summary>
 /// 创建数据库
 /// </summary>
 /// <param name="datasource"></param>
 /// <param name="pwd"></param>
 public static void CreateDB(string datasource, string pwd)
 {
     //创建一个数据库文件
     //string datasource = @"F:\Source\Solution_Wanxiang2011\WinAppTestSQLite\bin\Debug\test1234.db";
     System.Data.SQLite.SQLiteConnection.CreateFile(datasource);
     //连接数据库
     System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection();
     System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
     connstr.DataSource    = datasource;
     connstr.Password      = pwd;    // "adminwx";//设置密码,SQLite ADO.NET实现了数据库密码保护
     conn.ConnectionString = connstr.ToString();
     conn.Open();
     //创建表
 }
Esempio n. 28
0
 public void Connect(string pwd)
 {
     this._con = new SQLiteConnection();
     SQLiteConnectionStringBuilder connsb = new SQLiteConnectionStringBuilder();
     connsb.DataSource = this._fileName;
     connsb.Password = pwd;
     this._con.ConnectionString = connsb.ToString();
     this._con.Open();
     using (SQLiteCommand cmd = new SQLiteCommand(this._con))
     {
         cmd.CommandText = "Select * from MetaInfo";
         cmd.ExecuteReader();
     }
 }
Esempio n. 29
0
        /// <summary>
        /// 新しいインスタンスを初期化します。
        /// </summary>
        /// <param name="fileName">ファイル名</param>
        public Kbtter4Cache(string fileName)
        {
            var csb = new SQLiteConnectionStringBuilder()
            {
                DataSource = fileName,
                Version = 3,
                SyncMode = SynchronizationModes.Normal,
                JournalMode = SQLiteJournalModeEnum.Wal
            };
            Connection = new SQLiteConnection(csb.ToString());
            Connection.Open();

            CreateTables();
        }
Esempio n. 30
0
        private void buttonConnectOption_Click()
        {
            try
            {
                //-----< オプションを指定して接続 >-----
                var builder = new System.Data.SQLite.SQLiteConnectionStringBuilder
                {
                    DataSource  = CONNECTION_STRING,
                    SyncMode    = SynchronizationModes.Normal,
                    JournalMode = SQLiteJournalModeEnum.Persist,
                };
                string connectionString = builder.ToString();


                List <Artist> artists = new List <Artist>();
                //-----< オプションを指定して接続 >-----
                //using (var con = new SQLiteConnection(connectionString)) //上手く行かない・・・。
                using (var con = new SQLiteConnection(CONNECTION_STRING))
                {
                    con.Open();

                    using (var cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "SELECT * FROM artists";

                        using (var reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Artist _artist = new Artist();
                                _artist.ID   = reader.GetInt16(0);
                                _artist.Name = reader.GetString(1);
                                //_artist.CreatedAt = reader.GetValue(0);
                                //_artist.UpdatedAt = reader.GetValues(0);

                                artists.Add(_artist);
                            }
                        }
                    }
                }

                //-----< オプションを指定して接続 >-----
                myDataGrid01.ItemsSource = artists;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 31
0
        public LocalDb(ActivityInfoService service)
        {
            this.service = service;

            var builder = new SQLiteConnectionStringBuilder();
            builder.DataSource = Application.UserAppDataPath + "\\ActivityInfo.db";

            connection = new SQLiteConnection(builder.ToString());
            connection.Open();

            executeSQL("create table if not exists sync_regions (id TEXT, localVersion INTEGER)");
            executeSQL("create table if not exists sync_history (lastUpdate INTEGER)");

            regionEnum = service.GetSyncRegions().List.GetEnumerator();
        }
Esempio n. 32
0
        public void Test()
        {
            var connStrBuilder = new SQLiteConnectionStringBuilder();
            connStrBuilder.DataSource = dataSource;

            using (var conn = new SQLiteConnection(connStrBuilder.ToString())) {
                conn.Open();

                var command = new SQLiteCommand();
                command.Connection = conn;
                var sqlStr = "CREATE TABLE test(username varchar(20),password varchar(20))";
                command.CommandText = sqlStr;
                command.ExecuteNonQuery();
            }
        }
Esempio n. 33
0
        public DataProvider(String dataSource)
        {
            // build connection string
            SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
            builder.DataSource = dataSource;
            connectionString = builder.ToString();

            // 火险等级 1, 2, 3
            // 救援速度 1, 2, 3, 4, 5
            // 温度范围 1, 2
            attributeVals = new int[3][];
            attributeVals[0] = new int[]{1, 2, 3};
            attributeVals[1] = new int[]{1, 2, 3, 4, 5};
            attributeVals[2] = new int[]{1, 2};
        }
Esempio n. 34
0
        public void TestDapper()
        {
            var dataSource = @"test.sqlite";
            SQLiteConnection.CreateFile(dataSource);
            var builder = new SQLiteConnectionStringBuilder
            {
                DataSource = dataSource,
                LegacyFormat = false,
                Version = 3,
                SyncMode = SynchronizationModes.Off,
                JournalMode = SQLiteJournalModeEnum.Wal
            };

            using (var tran = new TransactionScope(TransactionScopeOption.Required))
            using (var connection = new SQLiteConnection(builder.ToString()))
            {
                connection.Open();
                CreateSampleSchema(connection);

                try
                {
                    connection.Execute("INSERT INTO table1 VALUES (@Id, @Name)", new { Id = 1, Name = "Name-1" });
                    connection.Execute("INSERT INTO table1 VALUES (@Id, @Name)", new { Id = 2, Name = "Name-2" });
                    connection.Execute("INSERT INTO table1 VALUES (@Id, @Name)", new { Id = 3, Name = "Name-3" });

                    dynamic dynamicObj = connection.Query("SELECT id, name FROM table1 LIMIT 1").FirstOrDefault();

                    Console.WriteLine("Id: {0}", dynamicObj.id);
                    Console.WriteLine("Name: {0}", dynamicObj.name);

                    var mappingObj = connection.Query<Table1>("SELECT id, name FROM table1 LIMIT 1").FirstOrDefault();

                    Console.WriteLine("Id: {0}", mappingObj.Id);
                    Console.WriteLine("Name: {0}", mappingObj.Name);

                    dynamic results = connection.Query("SELECT id, name FROM table1");
                    foreach (dynamic item in results)
                    {
                        Console.WriteLine(item);
                    }

                    tran.Complete();
                }
                catch
                {
                }
            }
        }
Esempio n. 35
0
        public SQLiteRepositoryClient()
        {
            var builder = new SQLiteConnectionStringBuilder
            {
                DataSource = dataSource,
                LegacyFormat = false
            };

            connection = new SQLiteConnection(builder.ToString());
            connection.Open();

            if(!ExistsTable(connection,Resource.TableName))
            {
                CreateSchema(connection);
            }
        }
Esempio n. 36
0
 /// <summary>
 /// 创建数据库
 /// </summary>
 /// <param name="dbName"></param>
 public void createDB(String datasource)
 {
     SQLiteConnection.CreateFile("databases/"+datasource+ ".db");
     SQLiteConnection conn = new SQLiteConnection();
     SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
     connstr.DataSource = "databases/" + datasource + ".db";
     conn.ConnectionString = connstr.ToString();
     conn.Open();
     //创建表
     SQLiteCommand cmd = new SQLiteCommand();
     string sql = "CREATE TABLE analysis(datea INTEGER,timea INTEGER,opena FLOAT ,higha FLOAT ,lowa FLOAT ,closea FLOAT ,vola INTEGER)";
     cmd.CommandText = sql;
     cmd.Connection = conn;
     int i= cmd.ExecuteNonQuery();
     conn.Close();
 }
Esempio n. 37
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="dataSource">数据文件</param>
 /// <param name="readOnly">是否只读</param>
 /// <param name="pooling">是否使用连接池</param>
 public SQLiteDatabase(string dataSource, bool readOnly, bool pooling)
 {
     if (!File.Exists(dataSource))
     {
         SQLiteConnection.CreateFile(dataSource);
     }
     SQLiteConnectionStringBuilder sb = new SQLiteConnectionStringBuilder
     {
         DataSource = dataSource,
         Version = 3,
         ReadOnly = readOnly,
         Pooling = pooling
     };
     ConnectionString = sb.ToString();
     __Conn = new SQLiteConnection(ConnectionString);
     __Conn.Open();
 }
Esempio n. 38
0
 public void TestConnection()
 {
     /*
       DbProviderFactory fact = DbProviderFactories.GetFactory("System.Data.SQLite");
       using (DbConnection cnn = fact.CreateConnection())
       {
     cnn.ConnectionString = "Data Source=test.db3";
     cnn.Open();
       }
       */
       var builder = new SQLiteConnectionStringBuilder();
       builder.DataSource = "test.db";
       SQLiteConnection sql = new SQLiteConnection(builder.ToString());
       sql.Open();
       sql.Close();
       sql.Dispose();
 }
Esempio n. 39
0
        public static bool Create(Book book)
        {
            string datasource = "test.db";
            SQLiteConnection.CreateFile(datasource);
            try
            {
                SQLiteConnection conn = new SQLiteConnection();
                SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
                connstr.DataSource = datasource;
                connstr.Password = "******";
                conn.ConnectionString = connstr.ToString();
                conn.Open();
                //using (SQLiteConnection conn = new SQLiteConnection("Data Source=test.db3"))
                //{

                    //conn.Open();

                    SQLiteCommand cmd = conn.CreateCommand();

                    cmd.CommandText = "insert into Book values(@ID,@BookName,@Price);";

                    cmd.Parameters.Add(new SQLiteParameter("ID", book.ID));

                    cmd.Parameters.Add(new SQLiteParameter("BookName", book.BookName));

                    cmd.Parameters.Add(new SQLiteParameter("Price", book.Price));

                    int i = cmd.ExecuteNonQuery();

                    return i == 1;

                //}

            }

            catch (Exception ex)
            {

                //Do any logging operation here if necessary

                //return false;
                throw ex;

            }

        }
Esempio n. 40
0
        /// <summary>
        /// 创建
        /// </summary>
        private void connectDatabase()
        {
            //连接
            System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection();
            System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
            connstr.DataSource = datasource;
            //connstr.Password = "******";//设置密码,SQLite ADO.NET实现了数据库密码保护
            conn.ConnectionString = connstr.ToString();
            conn.Open();

            //创建表格
            //System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
            //string sql = "CREATE TABLE control_authority(ElementName varchar(32), MinLevel int,ToStr varchar(32))";
            //cmd.CommandText = sql;
            //cmd.Connection = conn;
            //cmd.ExecuteNonQuery();
        }
Esempio n. 41
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InMemorySQLiteDatabase"/> class.
        /// </summary>
        public InMemorySQLiteDatabase()
        {
            var connectionStringBuilder = new SQLiteConnectionStringBuilder
            {
                DataSource = ":memory:",
                Version = 3,
                DefaultTimeout = 5,
                JournalMode = SQLiteJournalModeEnum.Memory,
                UseUTF16Encoding = true
            };
            ConnectionString = connectionStringBuilder.ToString();

            connectionManager = new SQLiteConnectionManager(connectionStringBuilder.ConnectionString);
            sharedConnection = new SQLiteConnection(connectionStringBuilder.ConnectionString);
            sharedConnection.OpenAndReturn();
            sqlRunner = new AdHocSqlRunner(() => sharedConnection.CreateCommand(), null, () => true);
        }
Esempio n. 42
0
        private DataManager()
        {
            _dbFile = "ohm.db";
            string currentPath;
            string absolutePath;

            currentPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
            absolutePath = System.IO.Path.Combine(currentPath, _dbFile);

            SQLiteConnectionStringBuilder connBuilder = new SQLiteConnectionStringBuilder();
            connBuilder.DataSource = absolutePath;
            connBuilder.Version = 3;
            // enable write ahead logging
            connBuilder.JournalMode = SQLiteJournalModeEnum.Wal;
            connBuilder.LegacyFormat = false;

            _sqliteConnection = new SQLiteConnection(connBuilder.ToString());
            _sqliteConnection.Open();
        }
Esempio n. 43
0
        public static SQLiteDataReader ExecuteDataReader(string sql, string db)
        {
            string datasource = db;// Application.StartupPath + "/nongli.db";

            //System.Data.SQLite.SQLiteConnection.CreateFile(datasource);
            //连接数据库
            System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection();
            System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
            connstr.DataSource    = datasource;
            connstr.Password      = "******";
            conn.ConnectionString = connstr.ToString();
            conn.Open();
            //取出数据
            System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
            cmd.Connection  = conn;
            cmd.CommandText = sql;
            System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader();
            return(reader);
        }
Esempio n. 44
0
        public static void Main(string[] args)
        {
            // create options builder


            /*builder. Mode = SqliteOpenMode.ReadOnly;
             * builder.Cache = SqliteCacheMode.Shared;
             * builder.ForeignKeys = true;
             * builder.RecursiveTriggers = true;*/
            // configure connection string
            //builder.UseSQLite(@"e:\StorageDB\StorageDB.sqlite");
            var b = new System.Data.SQLite.SQLiteConnectionStringBuilder(@"Data Source=e:\\StorageDB\\StorageDB.sqlite");

            b.CacheSize         = 8192;
            b.JournalMode       = System.Data.SQLite.SQLiteJournalModeEnum.Wal;
            b.ForeignKeys       = true;
            b.RecursiveTriggers = true;
            b.Enlist            = true;
            b.PageSize          = 4096;
            b.SyncMode          = System.Data.SQLite.SynchronizationModes.Full;
            b.ReadOnly          = true;
            b.Pooling           = true;


            var o = new LinqToDbConnectionOptionsBuilder();
            var p = o.UseSQLite(b.ToString());

            //System.Data.SQLite.SQLiteFunction
            // pass configured options to data connection constructor
            //List<Item> items = null;

            /*using (var dc = new SQLiteProvider(p.Build()))
             * {
             *
             *      //		items = (from i in dc.Items where i.ItemFileName.StartsWith("P") select i).ToList();
             * }
             *
             * foreach (var i in items)
             *      Console.WriteLine($"{i}");*/
            Console.ReadKey();
        }
Esempio n. 45
0
        /// <summary>
        /// 创建数据库
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public static bool CreatNewDB(string dbName)
        {
            try
            {
                if (dbName == "")
                {
                    dbName = "yanshanshuo.db";
                }
                string json = File.ReadAllText(ConfigurationManager.AppSettings["DataBaseCreate"]);
                List <Model.TableFrame> tables = LitJson.JsonMapper.ToObject <List <Model.TableFrame> >(json);;

                //判断数据文件是否存在,存在的话就删除
                string datasource = GetPath() + "App_Data\\" + dbName;
                System.Data.SQLite.SQLiteConnection.CreateFile(datasource);
                System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection();
                System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
                connstr.DataSource = datasource;
                //connstr.Password = "******";//设置密码,SQLite ADO.NET实现了数据库密码保护
                conn.ConnectionString = connstr.ToString();
                conn.Open();
                foreach (Model.TableFrame table in tables)
                {
                    string columnString = "";
                    foreach (Model.ColumnFrame c in table.column)
                    {
                        columnString += c.ColumnName + " " + c.DataType + " " + c.Condition + ",";
                    }
                    columnString = columnString.Substring(0, columnString.Length - 1);
                    //创建表
                    System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
                    string sql = "CREATE TABLE " + table.TableName + "(" + columnString + ")";
                    cmd.CommandText = sql;
                    cmd.Connection  = conn;
                    cmd.ExecuteNonQuery();
                }
                conn.Close();
                conn.Dispose();
                return(true);
            }
            catch (Exception ex) { return(false); }
        }
Esempio n. 46
0
        /// <summary>
        /// 查询配置
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static List <ConfigClass> query(string name)
        {
            try
            {
                List <ConfigClass> list = new List <ConfigClass>();
                SQLiteConnection   conn = new SQLiteConnection();
                System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
                connstr.DataSource    = SqlLiteHelper.getSQLiteConn();
                connstr.Password      = "******";           //设置密码,SQLite ADO.NET实现了数据库密码保护
                conn.ConnectionString = connstr.ToString();
                SQLiteCommand cmd = new SQLiteCommand(); //是不是很熟悉呢?

                DateTime StartComputerTime = DateTime.Now;

                cmd.Connection = conn;

                if (name == null)
                {
                    cmd.CommandText = "select * from t_config order by id asc";
                }
                else
                {
                    cmd.CommandText = "select * from t_config where name='" + name + "' order by id asc";
                }
                conn.Close();
                conn.Open();
                SQLiteDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    ConfigClass config = new ConfigClass();
                    config.Id          = reader["id"].ToString();
                    config.Name        = reader["name"].ToString();
                    config.FormalValue = reader["formalValue"].ToString();
                    config.TestValue   = reader["testValue"].ToString();
                    config.Remark      = reader["remark"].ToString();
                    list.Add(config);
                }
                conn.Close();
                return(list);
            }catch (Exception ex) { return(new List <ConfigClass>()); }
        }
        public void OpenDb()
        {
            if (_isopen && _conn != null)
            {
                return;
            }
            try
            {
                System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
                connstr.DataSource = this._kqfilepath;
                //connstr.Password = "******";
                //_conn = new SQLiteConnection(string.Format(@"Data Source={0};", _kqfilepath));
                _conn = new SQLiteConnection();
                _conn.ConnectionString = connstr.ToString();

                if (File.Exists(this._kqfilepath))
                {
                    _conn.Open();
                    _isopen = true;
                }
                else
                {
                    _conn.Open();
                    if (CreateTable())
                    {
                        _isopen = true;
                    }
                }
                return;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("打开KQDB失败");
                _isopen = false;
                if (_conn != null)
                {
                    _conn = null;
                }
                return;
            }
        }
Esempio n. 48
0
        static void Main(string[] args)
        {
            System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection();
            System.Data.SQLite.SQLiteConnectionStringBuilder connStr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
            connStr.DataSource    = @"F:\John's Dir\Principal Project\更新发布工具\Deployer\beta0.3\srvDB";
            conn.ConnectionString = connStr.ToString();
            conn.Open();
            string str = "select * from Deployer_WeblogicAppInfo_ML";

            System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
            cmd.CommandText = str;
            cmd.Connection  = conn;
            SQLiteDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

            while (reader.Read())
            {
                System.Console.WriteLine(reader.GetValue(1));
            }

            System.Console.Read();
        }
Esempio n. 49
0
        /// <summary>
        /// 修改配置
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public static bool update(ConfigClass config)
        {
            try
            {
                SQLiteConnection conn = new SQLiteConnection();
                System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
                connstr.DataSource    = SqlLiteHelper.getSQLiteConn();
                connstr.Password      = "******";//设置密码,SQLite ADO.NET实现了数据库密码保护
                conn.ConnectionString = connstr.ToString();
                SQLiteCommand comm = new SQLiteCommand(conn);
                comm.CommandText = "update t_config set testValue='" + config.FormalValue + "',formalValue='" + config.FormalValue + "' where name='" + config.Name + "'";

                conn.Open();
                int result = comm.ExecuteNonQuery();
                if (result > 0)
                {
                    return(true);
                }
                conn.Close();
                return(false);
            }
            catch (Exception ex) { return(false); }
        }
Esempio n. 50
0
 public static void InsertRangeData(Guid id, List <PublicProtocal.Coordinate> queue)
 {
     if (dataConnection == null)
     {
         dataConnection = new SQLiteConnection();
         SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
         connstr.DataSource = DbFileName;
         dataConnection.ConnectionString = connstr.ToString();
     }
     try
     {
         commonConnection.Open();
         SQLiteCommand cmd = new SQLiteCommand(commonConnection);
         cmd.CommandText = string.Format("Insert into CurveData([X],[Y],[id]) values(@p0,@p1,@p2)");
         cmd.Parameters.Add("@p0", System.Data.DbType.Decimal);
         cmd.Parameters.Add("@p1", System.Data.DbType.Decimal);
         cmd.Parameters.Add("@p2", System.Data.DbType.Decimal);
         cmd.CommandType = System.Data.CommandType.Text;
         cmd.ExecuteNonQuery();
         for (int i = 0; i < queue.Count; i++)
         {
             try
             {
                 cmd.Parameters["@p0"].Value = queue[i].X;
                 cmd.Parameters["@p1"].Value = queue[i].Y;
                 cmd.Parameters["@p2"].Value = id;
                 cmd.ExecuteNonQuery();
             }
             catch { continue; }
         }
     }
     catch { return; }
     finally
     {
         commonConnection.Close();
     }
 }
Esempio n. 51
0
 public static void InsertObject <T>(T instance) where T : BaseObject
 {
     try
     {
         string tableName = typeof(T).Name;//;.Substring(typeof(T).Name.LastIndexOf('.'));
         if (commonConnection == null)
         {
             commonConnection = new SQLiteConnection();
             SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
             connstr.DataSource = DbFileName;
             commonConnection.ConnectionString = connstr.ToString();
         }
         commonConnection.Open();
         SQLiteCommand cmd = new SQLiteCommand(commonConnection);
         cmd.CommandText = BuildInsertCommand(tableName, instance);
         cmd.ExecuteNonQuery();
         commonConnection.Close();
     }
     catch (Exception e)
     {
         commonConnection.Close();
         throw e;
     }
 }
Esempio n. 52
0
        private void SqliteTest(object sender, RoutedEventArgs e)
        {
            string datasource = "test.db";

            System.Data.SQLite.SQLiteConnection.CreateFile(datasource);
            System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection();
            System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
            connstr.DataSource = datasource;
            connstr.CacheSize  = 1024;
            //  connstr.Password = "******";//设置密码,SQLite ADO.NET实现了数据库密码保护
            conn.ConnectionString = connstr.ToString();
            conn.Open();

            System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
            string sql = "CREATE TABLE test(username varchar(20),password varchar(20))";

            cmd.CommandText = sql;
            cmd.Connection  = conn;
            cmd.ExecuteNonQuery();

            sql             = "INSERT INTO test VALUES('a','b')";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();

            sql             = "SELECT * FROM test";
            cmd.CommandText = sql;
            System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader();
            StringBuilder sb = new StringBuilder();

            while (reader.Read())
            {
                sb.Append("username:"******"\n")
                .Append("password:").Append(reader.GetString(1));
            }
            MessageBox.Show(sb.ToString());
        }
Esempio n. 53
0
 public static void DeleteObjectById <T>(Guid id)
 {
     try
     {
         string tableName = typeof(T).Name;
         if (commonConnection == null)
         {
             commonConnection = new SQLiteConnection();
             SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
             connstr.DataSource = DbFileName;
             commonConnection.ConnectionString = connstr.ToString();
         }
         commonConnection.Open();
         SQLiteCommand cmd = new SQLiteCommand(commonConnection);
         cmd.CommandText = "Delete  from " + tableName + " where id='" + id.ToString() + "'";
         cmd.ExecuteNonQuery();
         commonConnection.Close();
     }
     catch (Exception e)
     {
         commonConnection.Close();
         throw e;
     }
 }
Esempio n. 54
0
        public static void CheckDataFile(string datasource)
        {
            //string datasource = Application.StartupPath + "\\data.db";
            System.Data.SQLite.SQLiteConnection.CreateFile(datasource);
            //连接数据库
            System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection();
            System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
            connstr.DataSource = datasource;
            //connstr.Password = "******";//设置密码,SQLite ADO.NET实现了数据库密码保护
            conn.ConnectionString = connstr.ToString();
            conn.Open();
            //创建表
            System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
            string sql = "CREATE TABLE billInfo (BillID varchar(50) PRIMARY KEY,SiteName varchar(50),SiteUserName varchar(50),TotalMoney decimal(5,2),YearRete decimal(5,2),Deadline interger ,DeadlineType interger,ReceivedPeriod interger,ReceivablePeriod interger,ReceivablePrincipalAndInterest decimal(5,2),ReceivedPrincipalAndInterest decimal(5,2),WayOfRepayment interger,Reward decimal(5,2),BeginDay varchar(20),EndDay varchar(20),YuQiCount interger,Deleted interger,Flag interger,Remark varchar(200),UpdateTime datetime,CreateTime datetime)";

            cmd.CommandText = sql;
            cmd.Connection  = conn;
            cmd.ExecuteNonQuery();

            sql             = "Create Table billdetail(BillDetailID varchar(50) PRIMARY KEY,BillID varchar(50),Periods varchar(50),ReceivableDay varchar(20),ReceivedDay varchar(20),ReceivablePrincipalAndInterest decimal(5,2),ReceivableInterest decimal(5,2),ReceivedPrincipalAndInterest decimal(5,2),IsYuQi interger ,Deleted interger,Flag interger,UpdateTime datetime,CreateTime datetime)";
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
            conn.Close();
        }
Esempio n. 55
0
        void TestSQLite2()
        {
            try
            {
                //创建一个数据库文件

                string datasource = "./test.db";

                System.Data.SQLite.SQLiteConnection.CreateFile(datasource);

                //连接数据库

                System.Data.SQLite.SQLiteConnection conn =

                    new System.Data.SQLite.SQLiteConnection();

                System.Data.SQLite.SQLiteConnectionStringBuilder connstr =

                    new System.Data.SQLite.SQLiteConnectionStringBuilder();

                connstr.DataSource = datasource;

                //  connstr.Password = "******";//设置密码,SQLite ADO.NET实现了数据库密码保护

                conn.ConnectionString = connstr.ToString();

                conn.Open();

                //创建表

                System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();

                string sql = "CREATE TABLE test(username varchar(20),password text)";

                cmd.CommandText = sql;

                cmd.Connection = conn;

                cmd.ExecuteNonQuery();

                //插入数据
                SQLiteCommand cmd2 = new SQLiteCommand("INSERT INTO test(username, password) VALUES('dotnetthink', ?)", conn);
                cmd2.Parameters.Add("password");

                byte[] password = new byte[] { 1, 2, 3, 4, 5 };

                cmd2.Parameters["password"].Value = password;

                cmd2.ExecuteNonQuery();

                //取出数据

                sql = "SELECT * FROM test";

                cmd.CommandText = sql;

                System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader();

                StringBuilder sb = new StringBuilder();

                while (reader.Read())
                {
                    sb.Append("username:"******"\n")

                    .Append("password:").Append(reader.GetString(1));
                }

                MessageBox.Show(sb.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 56
0
        private void button1_Click(object sender, EventArgs e)
        {
            //创建一个数据库文件

            string datasource = "test.db";

            System.Data.SQLite.SQLiteConnection.CreateFile(datasource);

            //连接数据库

            System.Data.SQLite.SQLiteConnection conn =

                new System.Data.SQLite.SQLiteConnection();

            System.Data.SQLite.SQLiteConnectionStringBuilder connstr =

                new System.Data.SQLite.SQLiteConnectionStringBuilder();

            connstr.DataSource = datasource;

            connstr.Password = "******";//设置密码,SQLite ADO.NET实现了数据库密码保护

            conn.ConnectionString = connstr.ToString();

            conn.Open();

            //创建表

            System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();

            string sql = "CREATE TABLE test(username varchar(20),password varchar(20))";

            cmd.CommandText = sql;

            cmd.Connection = conn;

            cmd.ExecuteNonQuery();

            //插入数据

            sql = "INSERT INTO test VALUES(’dotnetthink’,'mypassword’)";

            cmd.CommandText = sql;

            cmd.ExecuteNonQuery();

            //取出数据

            sql = "SELECT * FROM test";

            cmd.CommandText = sql;

            System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader();

            StringBuilder sb = new StringBuilder();

            while (reader.Read())
            {
                sb.Append("username:"******"\n")

                .Append("password:").Append(reader.GetString(1));
            }

            MessageBox.Show(sb.ToString());
        }
Esempio n. 57
0
        private void butlogin_Click(object sender, EventArgs e)
        {
            if (AuthorityType.Text == "supuser")
            {
                //string user = this.textBoxX1.Text.ToString();
                //string pwd = this.textBoxX2.Text.ToString();
                string users;
                string pwds;
                bool   flagshow = false;
                string strConn  = System.Windows.Forms.Application.StartupPath + "//Database.db";
                //string strConn = "C:/Users/dell/Desktop/renwu5/v3_4.9/Database.db";
                System.Data.SQLite.SQLiteConnectionStringBuilder strBuild = new System.Data.SQLite.SQLiteConnectionStringBuilder();
                strBuild.DataSource = strConn;
                System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection(strBuild.ToString());

                conn.Open();
                string        cmd = " select * from FW_User where U_Roles=='supuser'";
                SQLiteCommand com = new SQLiteCommand();
                //SqlCommand com = new SqlCommand();
                com.CommandText = cmd;         //commandtext属性
                com.Connection  = conn;        //connection属性
                int u = com.ExecuteNonQuery(); //执行sql的方法,它的返回值类型为int型。多用于执行增加,删除,修改数据。返回受影响的行数
                //ExecuteReader()它的返回类型为SqlDataReader,此方法用于用户进行的查询操作。使用SqlDataReader对象的Read();方法进行逐行读取
                Console.WriteLine(u + "===="); //看看影响数据库表中几行
                SQLiteDataReader reader = com.ExecuteReader();
                while (reader.Read())          //从数据库读取用户信息
                {
                    users = reader["U_Name"].ToString();
                    pwds  = reader["U_Password"].ToString();
                    if (users.Trim() == textBoxX1.Text & pwds.Trim() == textBoxX2.Text)
                    {
                        flagshow = true; //用户名存在于数据库,则为true
                    }
                }
                reader.Close();
                conn.Close();
                if (flagshow == true)
                {
                    //MessageBox.Show("登录成功!");
                    this.Close();
                    new FrmMain().Show();
                }
                else
                {
                    MessageBox.Show("用户不存在或密码错误!", "提示");
                    return;
                }
            }
            else if (AuthorityType.Text == "comuser")
            {
                string users;
                string pwds;
                bool   flagshow = false;
                string strConn  = System.Windows.Forms.Application.StartupPath + "//Database.db";
                //string strConn = "C:/Users/dell/Desktop/renwu5/v3_4.9/Database.db";
                System.Data.SQLite.SQLiteConnectionStringBuilder strBuild = new System.Data.SQLite.SQLiteConnectionStringBuilder();
                strBuild.DataSource = strConn;
                System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection(strBuild.ToString());

                conn.Open();
                string        cmd = " select * from FW_User where U_Roles=='comuser'";
                SQLiteCommand com = new SQLiteCommand();
                //SqlCommand com = new SqlCommand();
                com.CommandText = cmd;         //commandtext属性
                com.Connection  = conn;        //connection属性
                int u = com.ExecuteNonQuery(); //执行sql的方法,它的返回值类型为int型。多用于执行增加,删除,修改数据。返回受影响的行数
                //ExecuteReader()它的返回类型为SqlDataReader,此方法用于用户进行的查询操作。使用SqlDataReader对象的Read();方法进行逐行读取
                Console.WriteLine(u + "===="); //看看影响数据库表中几行
                SQLiteDataReader reader = com.ExecuteReader();
                while (reader.Read())          //从数据库读取用户信息
                {
                    users = reader["U_Name"].ToString();
                    pwds  = reader["U_Password"].ToString();
                    if (users.Trim() == textBoxX1.Text & pwds.Trim() == textBoxX2.Text)
                    {
                        flagshow = true; //用户名存在于数据库,则为true
                    }
                }
                reader.Close();
                conn.Close();
                if (flagshow == true)
                {
                    MessageBox.Show("登录成功!");
                    this.Close();
                    new FrmMain1().Show();
                }
                else
                {
                    MessageBox.Show("用户不存在或密码错误!", "提示");
                    return;
                }
            }
            else if (AuthorityType.Text == "")
            {
                MessageBox.Show("请选择权限!", "提示");
            }
        }