static void EXECUDFExample()
        {
            using (SqlDatabaseConnection cnn = new SqlDatabaseConnection("schemaname=db;uri=file://" + ExampleDatabaseFile + "; "))
            {
                cnn.Open();
                // Available from version 2.7
                using (SqlDatabaseCommand cmd = new SqlDatabaseCommand())
                {
                    cmd.Connection = cnn;

                    // SELECT - ExecScalarUDF
                    // ExecScalarUDF is called once for each row for each call.
                    // Following will call the event handler twice as ExecScalarUDF is called twice.
                    DataTable dt = new DataTable();
                    cmd.CommandText = "SELECT *, ExecScalarUDF('Exec1', Phone) AS ANumber, ExecScalarUDF('Exec2', 1, 2, @Param1, FirstName ) AS ExampleText FROM Customers LIMIT 10;";
                    cmd.Parameters.AddWithValue("@Param1", 3);
                    SqlDatabaseDataReader dr = cmd.ExecuteReader();
                    for (int c = 0; c < dr.VisibleFieldCount; c++)
                    {
                        Console.Write(dr.GetName(c) + "\t");
                    }
                    Console.WriteLine(Environment.NewLine + "----------------------");
                    while (dr.Read())
                    {
                        for (int c = 0; c < dr.VisibleFieldCount; c++)
                        {
                            Console.Write(dr.GetValue(c) + "\t");
                        }
                        Console.WriteLine("");
                    }
                    ;
                }
            }
        }
Пример #2
0
        public int ExportTable(string FilePathAndName, bool AppendToFile = false)
        {
            int _row_count = 0;

            using (SqlDatabaseCommand cmd = new SqlDatabaseCommand(SQLDatabaseConnection))
            {
                if (SQLDatabaseTransaction != null)
                {
                    cmd.Transaction = SQLDatabaseTransaction;
                }

                cmd.CommandText = string.Format("SELECT * FROM [{0}].[{1}]", SchemaName, TableName);
                using (CsvWriter = new CsvFileWriter(FilePathAndName, AppendToFile, Encoding.UTF8))
                {
                    SqlDatabaseDataReader dataReader  = cmd.ExecuteReader();
                    List <string>         ColumnNames = new List <string>();
                    // Write header i.e. column names
                    for (int i = 0; i < dataReader.VisibleFieldCount; i++)
                    {
                        if (dataReader.GetFieldType(i) != Type.GetType("byte[]")) // BLOB will not be written
                        {
                            ColumnNames.Add(dataReader.GetName(i));               //maintain columns in the same order as the header line.
                            CsvWriter.AddField(dataReader.GetName(i));
                        }
                    }
                    CsvWriter.SaveAndCommitLine();
                    // Write data i.e. rows.
                    while (dataReader.Read())
                    {
                        foreach (string ColumnName in ColumnNames)
                        {
                            CsvWriter.AddField(dataReader.GetString(dataReader.GetOrdinal(ColumnName))); //dataReader.GetOrdinal(ColumnName) provides the position.
                        }
                        CsvWriter.SaveAndCommitLine();
                        _row_count++; //Increase row count to track number of rows written.
                    }
                }
            }

            return(_row_count);
        }
Пример #3
0
        public long ExportTable(string filePathAndName, bool appendToFile = false)
        {
            SQLDatabaseConnection.Open();
            long rowCount = 0;

            using (SqlDatabaseCommand cmd = new SqlDatabaseCommand(SQLDatabaseConnection))
            {
                if (SQLDatabaseTransaction != null)
                {
                    cmd.Transaction = SQLDatabaseTransaction;
                }

                cmd.CommandText = $@"SELECT * FROM [{SchemaName}].[{TableName}]";
                using (DelimitedWriter = new DelimitedFileWriter(filePathAndName, appendToFile, Encoding.UTF8))
                {
                    // set variables
                    DelimitedWriter.Delimiter = Delimiter;
                    DelimitedWriter.QuoteWrap = ReplicationFormData.QuoteWrap;
                    DelimitedWriter.NullValue = ReplicationFormData.NullValue;

                    // write custom header to file if not empty
                    if (!string.IsNullOrWhiteSpace(ReplicationFormData.CustomHeader))
                    {
                        DelimitedWriter.WriteLineToFile(ReplicationFormData.CustomHeader);
                    }

                    SqlDatabaseDataReader dataReader  = cmd.ExecuteReader();
                    List <string>         columnNames = new List <string>();
                    // Write header i.e. column names
                    for (int i = 0; i < dataReader.VisibleFieldCount; i++)
                    {
                        var name = dataReader.GetName(i);
                        if (dataReader.GetFieldType(i) != Type.GetType("byte[]") &&
                            name != Constants.ReplicationRecordId &&
                            name != Constants.ReplicationVersionIds &&
                            name != Constants.ReplicationVersionRecordId) // BLOB will not be written
                        {
                            columnNames.Add(name);                        //maintain columns in the same order as the header line.
                            DelimitedWriter.AddField(name);
                        }
                    }

                    DelimitedWriter.SaveAndCommitLine();
                    // Write data i.e. rows.
                    while (dataReader.Read())
                    {
                        foreach (string columnName in columnNames)
                        {
                            DelimitedWriter.AddField(
                                dataReader.GetString(
                                    dataReader.GetOrdinal(
                                        columnName))); //dataReader.GetOrdinal(ColumnName) provides the position.
                        }

                        DelimitedWriter.SaveAndCommitLine();
                        rowCount++; //Increase row count to track number of rows written.
                    }
                }
            }

            return(rowCount);
        }
        static void EncryptionDecryption()
        {
            Console.WriteLine("*************** Encrypted File Example *******************");
            using (SqlDatabaseConnection cnn = new SqlDatabaseConnection("SchemaName=db;uri=file://Encrypted.db;"))
            {
                cnn.Open();

                using (SqlDatabaseCommand cmd = new SqlDatabaseCommand(cnn))
                {
                    //Entire Database File will be encrypted using AES 256
                    cmd.CommandText = "SYSCMD Key='SecretPassword';";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "Create table if not exists Users(id integer primary key autoincrement, Username Text, Password Text); ";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "INSERT INTO Users values(NULL, @username, @password);";
                    cmd.Parameters.AddWithValue("@username", "sysdba");
                    cmd.Parameters.AddWithValue("@password", "SecretPassword");
                    cmd.ExecuteNonQuery();
                }
            }


            using (SqlDatabaseConnection cnn = new SqlDatabaseConnection("SchemaName=db;uri=file://Encrypted.db;"))
            {
                cnn.Open();
                using (SqlDatabaseCommand cmd = new SqlDatabaseCommand(cnn))
                {
                    //Entire Database File will be encrypted using AES 256
                    cmd.CommandText = "SYSCMD Key = 'SecretPassword'; ";  //If incorrect password library will not respond.
                    cmd.ExecuteNonQuery();

                    // COLLATE BINARY performs case sensitive search for password
                    // see http://www.sqldatabase.net/docs/syscmd.aspx for available collation sequences.

                    cmd.CommandText = "SELECT Id FROM Users WHERE Username = @username AND Password = @password COLLATE BINARY;";
                    cmd.Parameters.AddWithValue("@username", "sysdba");
                    cmd.Parameters.AddWithValue("@password", "SecretPassword");
                    Console.WriteLine("User Found {0}", cmd.ExecuteScalar() == null ? "No" : "Yes");
                }
            }

            Console.Write(string.Empty);
            Console.WriteLine("*************** Encrypted Column Example *******************");

            string RandomUserName = "******" + System.IO.Path.GetRandomFileName();

            using (SqlDatabaseConnection cnn = new SqlDatabaseConnection("SchemaName=db;uri=file://EncryptedColumn.db;"))
            {
                cnn.Open();
                using (SqlDatabaseCommand cmd = new SqlDatabaseCommand(cnn))
                {
                    cmd.CommandText = "CREATE TABLE IF NOT EXISTS UsersCreditCards(Name Text Primary Key, CreditCardNumber Text); ";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "INSERT INTO UsersCreditCards values(@Name, EncryptText(@CreditCardNumber , 'SecretPassword'));";
                    cmd.Parameters.AddWithValue("@Name", RandomUserName);
                    cmd.Parameters.AddWithValue("@CreditCardNumber", "1234-5678");
                    cmd.ExecuteNonQuery();
                }
            }

            using (SqlDatabaseConnection cnn = new SqlDatabaseConnection("SchemaName=db;uri=file://EncryptedColumn.db;"))
            {
                cnn.Open();
                using (SqlDatabaseCommand cmd = new SqlDatabaseCommand(cnn))
                {
                    cmd.CommandText = "SELECT DecryptText(CreditCardNumber , 'SecretPassword') AS [CreditCardNumber] FROM UsersCreditCards WHERE Name = @Name LIMIT 1;";
                    cmd.Parameters.AddWithValue("@Name", RandomUserName);
                    Console.WriteLine("User {0} Credit Card Number is : {1}", RandomUserName, cmd.ExecuteScalar());

                    Console.WriteLine("*************** All Users *******************");
                    cmd.CommandText = "SELECT Name, DecryptText(CreditCardNumber , 'SecretPassword') AS CreditCardNumber FROM UsersCreditCards;";
                    SqlDatabaseDataReader dr = cmd.ExecuteReader();
                    for (int c = 0; c < dr.VisibleFieldCount; c++)
                    {
                        Console.Write(dr.GetName(c) + "\t");
                    }
                    Console.WriteLine(Environment.NewLine + "----------------------");
                    while (dr.Read())
                    {
                        for (int c = 0; c < dr.VisibleFieldCount; c++)
                        {
                            Console.Write(dr.GetValue(c) + "\t");
                        }
                        Console.WriteLine("");
                    }
                    ;
                }
            }

            if (File.Exists("Encrypted.db"))
            {
                File.Delete("Encrypted.db");
            }

            if (File.Exists("EncryptedColumn.db"))
            {
                File.Delete("EncryptedColumn.db");
            }
        }
        static void MultiThreading()
        {
            using (SqlDatabaseConnection cnn = new SqlDatabaseConnection("schemaname=db;uri=file://@memory;")) // In Memory database.
            {
                try
                {
                    cnn.Open();
                    if (cnn.State != ConnectionState.Open)
                    {
                        Console.WriteLine("Unable to open connection.");
                        return;
                    }
                }
                catch (SqlDatabaseException e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                    return;
                }

                using (SqlDatabaseCommand cmd = new SqlDatabaseCommand())
                {
                    cmd.Connection  = cnn;
                    cmd.CommandText = "CREATE TABLE IF NOT EXISTS TestTable (ThreadId Integer, Id Integer, RandomText Text, ByteArray Blob);";
                    cmd.ExecuteNonQuery();
                }

                Random rnd = new Random();
                Parallel.For(0, Environment.ProcessorCount,
                             new ParallelOptions
                {
                    MaxDegreeOfParallelism = Environment.ProcessorCount
                },
                             i => {
                    using (SqlDatabaseCommand cmd = new SqlDatabaseCommand())
                    {
                        cmd.Connection = cnn;

                        string RandomPathForText = System.IO.Path.GetRandomFileName();

                        cmd.CommandText = "INSERT INTO TestTable VALUES (@ThreadId, @Id, @RandomText, @ByteArray);";
                        if (!cmd.Parameters.Contains("@ThreadId"))
                        {
                            cmd.Parameters.AddWithValue("@ThreadId", System.Threading.Thread.CurrentThread.ManagedThreadId);
                        }
                        else
                        {
                            cmd.Parameters["@ThreadId"].Value = System.Threading.Thread.CurrentThread.ManagedThreadId;
                        }

                        if (!cmd.Parameters.Contains("@Id"))
                        {
                            cmd.Parameters.AddWithValue("@Id", rnd.Next(1, 100));
                        }
                        else
                        {
                            cmd.Parameters["@Id"].Value = rnd.Next(1, 100);
                        }

                        if (!cmd.Parameters.Contains("@RandomText"))
                        {
                            cmd.Parameters.AddWithValue("@RandomText", RandomPathForText);
                        }
                        else
                        {
                            cmd.Parameters["@RandomText"].Value = RandomPathForText;
                        }

                        if (!cmd.Parameters.Contains("@ByteArray"))
                        {
                            cmd.Parameters.AddWithValue("@ByteArray", Encoding.UTF8.GetBytes(RandomPathForText));
                        }
                        else
                        {
                            cmd.Parameters["@ByteArray"].Value = Encoding.UTF8.GetBytes(RandomPathForText);
                        }

                        cmd.ExecuteNonQuery();
                    }
                });


                using (SqlDatabaseCommand cmd = new SqlDatabaseCommand(cnn))
                {
                    cmd.CommandText = "SELECT * FROM TestTable; ";
                    cmd.ExecuteNonQuery();
                    SqlDatabaseDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        for (int c = 0; c < dr.VisibleFieldCount; c++)
                        {
                            //Console.Write(Encoding.UTF8.GetString(dr.GetFieldValue<byte[]>(c)) + "\t");
                            //byte[] byteArray = (byte[])dr.GetValue(c);
                            if (dr.GetName(c).Equals("ByteArray"))
                            {
                                Console.Write(Encoding.UTF8.GetString(dr.GetFieldValue <byte[]>(c)) + "\t");
                            }
                            else
                            {
                                Console.Write(dr.GetValue(c) + "\t");
                            }
                        }
                        Console.WriteLine("");
                    }
                }
            }
        }
Пример #6
0
        private void CreateDropTable_Click(object sender, EventArgs e)
        {
            //Create file name
            string dbfilepath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "tempdb.db");

            //Connection string
            string strCon = "schemaname=db;uri=file://" + dbfilepath + ";";

            using (SqlDatabaseConnection cnn = new SqlDatabaseConnection(strCon))
            {
                //Either open the existing database file or create new.
                //Other option is DatabaseFileMode.OpenIfExists in which new file is not created.
                cnn.DatabaseFileMode = DatabaseFileMode.OpenOrCreate;

                //Since we are creating new table, database must be opened in ReadWrite mode.
                cnn.DatabaseMode = DatabaseMode.ReadWrite;

                try
                {
                    cnn.Open();
                } catch (SqlDatabaseException dbe)
                {
                    Debug.WriteLine(dbe.Message);
                    return;
                }

                // Check if database connection is open before we create command object to query.
                if (cnn.State == ConnectionState.Open)
                {
                    using (SqlDatabaseCommand cmd = new SqlDatabaseCommand())
                    {
                        // Assign the connection to this command object.
                        cmd.Connection = cnn;

                        cmd.CommandText = "DROP TABLE IF EXISTS ATableName; ";
                        cmd.ExecuteNonQuery();

                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine("CREATE TABLE IF NOT EXISTS ATableName ");
                        sb.AppendLine(" ( ");
                        sb.AppendLine(" Id INTEGER PRIMARY KEY AUTOINCREMENT "); // Column with integer data types
                        sb.AppendLine(" , ProductName TEXT ");                   // Column with Text data type with no max number of characters same as varchar or string
                        sb.AppendLine(" , Price REAL ");                         // double, float or decimal datatype used for money.
                        sb.AppendLine(" , Picture BLOB ");                       // BLOB data type for bytes.
                        sb.AppendLine(" , MoreInfo NONE ");                      // Not sure and no preference
                        sb.AppendLine(" ) ");
                        cmd.CommandText = sb.ToString();
                        cmd.ExecuteNonQuery();

                        //SYS_OBJECTS Stores the table , you can verify that table exists or get the original sql from sqltext column.
                        sb.Clear();
                        sb.AppendLine("SELECT type [Object Type], crdatetime AS [DateTime Created], tablename [Table Name] FROM SYS_OBJECTS WHERE type = 'table' AND Name = 'ATableName';");
                        cmd.CommandText = sb.ToString();
                        SqlDatabaseDataReader dr = cmd.ExecuteReader();
                        while (dr.Read())
                        {
                            // Column Names using GetName function
                            for (int c = 0; c < dr.VisibleFieldCount; c++)
                            {
                                Debug.Write(dr.GetName(c).ToString() + "\t");
                            }
                            Debug.WriteLine(Environment.NewLine + "-------------------------------------------");

                            // Row values
                            for (int c = 0; c < dr.VisibleFieldCount; c++)
                            {
                                Debug.Write(dr.GetValue(c).ToString() + "\t");
                            }
                        }

                        // Drop the table
                        sb.Clear();
                        sb.Append("DROP TABLE IF EXISTS ATableName ; ");
                        cmd.CommandText = sb.ToString();
                        cmd.ExecuteNonQuery();
                    }
                }
            }

            try
            {
                if (File.Exists(dbfilepath))
                {
                    File.Delete(dbfilepath);
                }
            } catch (IOException ex)
            {
                throw ex;
            }
        }