コード例 #1
0
        private Byte[] readBinaryField(OleDbDataReader reader, int fieldNo)
        {
            const int bufSize  = 1000;
            int       startIdx = 0;

            Byte[] buf = new Byte[bufSize];

            MemoryStream ms = new MemoryStream();

            try
            {
                long getLength = reader.GetBytes(fieldNo, startIdx, buf, 0, bufSize);
                //Console.WriteLine("buf=" + getDumpStr(buf));
                ms.Write(buf, 0, (int)getLength);

                // バイナリフィールドから読み込めたバイト数がバッファサイズと同じであれば、まだ続きがあるということ
                while (getLength >= bufSize)
                {
                    startIdx  = startIdx + bufSize;
                    getLength = reader.GetBytes(fieldNo, startIdx, buf, 0, bufSize);
                    // Console.WriteLine("buf=" + getDumpStr(buf));
                    ms.Write(buf, 0, (int)getLength);
                }

                return(ms.GetBuffer());
            }
            catch (Exception ex)
            {
                Console.WriteLine("バイナリフィールドの読み込みで例外が発生しました:");
                Console.WriteLine(ex.Message);
            }

            return(new byte[0]);
        }
コード例 #2
0
ファイル: AccèsSQL.cs プロジェクト: kevmarzin/ProjetBD
        private static List <object> FetchRow(string constr, string query)
        {
            OleDbConnection dbCon = new OleDbConnection(constr);

            dbCon.Open();
            OleDbCommand    cmd     = new OleDbCommand(query, dbCon);
            OleDbDataReader lecteur = cmd.ExecuteReader();
            List <object>   ob      = new List <object>();

            while (lecteur.Read())
            {
                #region lecture des données
                for (int i = 0; i < lecteur.VisibleFieldCount; i++)
                {
                    if (lecteur.IsDBNull(i))
                    {
                        ob.Add(null);
                    }
                    else
                    {
                        Type t = lecteur.GetFieldType(i);
                        switch (t.Name)
                        {
                        case "Byte[]":
                            long   len = lecteur.GetBytes(i, 0, null, 0, 0);
                            byte[] im  = new byte[len];
                            lecteur.GetBytes(i, 0, im, 0, (int)len);
                            ob.Add(im);
                            break;

                        case "Int16":
                            ob.Add(lecteur.GetInt16(i));
                            break;

                        case "Int32":
                            ob.Add(lecteur.GetInt32(i));
                            break;

                        case "Decimal":
                            ob.Add(lecteur.GetDecimal(i));
                            break;

                        case "String":
                            ob.Add(lecteur.GetString(i));
                            break;

                        default:
                            ob.Add(null);
                            break;
                        }
                    }
                }
                #endregion
            }
            return(ob);
        }
コード例 #3
0
ファイル: ado_dm.cs プロジェクト: wangyakai01/APSIMClassic
 //============================================================================
 /// <summary>
 /// Return the value of this column as a byte array.
 /// </summary>
 /// <param name="col">Column index 0->n</param>
 /// <returns>The byte array. byte[1] if not found.</returns>
 //============================================================================
 public override Byte[] ColAsBytes(int col)
 {
     Byte[] result = new Byte[1];
     if (reader != null)
     {
         if (reader.FieldCount >= col + 1)
         {
             long size = reader.GetBytes(col, 0, null, 0, 0);
             result = new Byte[size];
             reader.GetBytes(col, 0, result, 0, (int)size);
         }
     }
     return(result);
 }
コード例 #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string strID = Request.QueryString["id"];

        if (strID == null)
        {
            Response.Clear();
            Response.End();
            return;
        }

        Response.Clear();                                                           // Required
        Response.ContentType = "application/msword";                                // Required
        Response.AddHeader("Content-Disposition", "attachment; filename=down.doc"); // Required

        string          connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|demo.mdb";
        OleDbConnection conn       = new OleDbConnection(connstring);

        conn.Open();
        OleDbCommand cmd = new OleDbCommand();

        cmd.Connection  = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select FileBin from documents where ID = @id";
        OleDbParameter spID = new OleDbParameter("@id", OleDbType.Integer);

        spID.Value = strID;
        cmd.Parameters.Add(spID);
        OleDbDataReader dr        = cmd.ExecuteReader();
        int             iFileSize = 0;

        if (dr.Read())
        {
            int    FileCol = 0; // the column # of the BLOB field
            Byte[] b       = new Byte[(dr.GetBytes(FileCol, 0, null, 0, int.MaxValue))];
            dr.GetBytes(FileCol, 0, b, 0, b.Length);
            iFileSize = b.Length;
            System.IO.Stream fs = Response.OutputStream;
            fs.Write(b, 0, b.Length);
            fs.Close();
        }
        dr.Close();
        conn.Close();
        Response.AppendHeader("Content-Length", iFileSize.ToString()); // Required
        Response.End();                                                // Required
    }
コード例 #5
0
ファイル: DataReader.cs プロジェクト: jakedw7/iAM
 public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
 {
     if (SDR != null)
     {
         return(SDR.GetBytes(i, fieldOffset, buffer, bufferoffset, length));
     }
     else
     {
         return(ODR.GetBytes(i, fieldOffset, buffer, bufferoffset, length));
     }
 }
コード例 #6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] != null && Request.QueryString["id"].Length > 0)
        {
            string id      = Request.QueryString["id"];
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|demo_paper.mdb";
            string strSql  = "select Word from stream where id =" + id;

            OleDbConnection conn = new OleDbConnection(strConn);
            OleDbCommand    cmd  = new OleDbCommand(strSql, conn);
            conn.Open();
            cmd.CommandType = CommandType.Text;
            OleDbDataReader reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                long   num = reader.GetBytes(0, 0, null, 0, Int32.MaxValue) - 1;
                Byte[] b   = new Byte[num];
                reader.GetBytes(0, 0, b, 0, b.Length);
                Response.ContentType = "Application/msword";

                Response.AddHeader("Content-Disposition", "attachment; filename=down.doc");
                Response.AddHeader("Content-Length", num.ToString());
                this.Response.Clear();
                System.IO.Stream fs = this.Response.OutputStream;
                fs.Write(b, 0, b.Length);
                fs.Close();
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "script1", "alert('The specified file does not exist.');location.href='Default.aspx';", true);
            }
            reader.Close();
            conn.Close();
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "script1", "alert('The ID parameter cannot be null.');location.href='Default.aspx';", true);
        }
    }
コード例 #7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] != null && Request.QueryString["id"].Length > 0)
        {
            string id      = Request.QueryString["id"];
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|demo_paper.mdb";
            string strSql  = "select Word from stream where id =" + id;

            OleDbConnection conn = new OleDbConnection(strConn);
            OleDbCommand    cmd  = new OleDbCommand(strSql, conn);
            conn.Open();
            cmd.CommandType = CommandType.Text;
            OleDbDataReader reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                long   num = reader.GetBytes(0, 0, null, 0, Int32.MaxValue) - 1;//
                Byte[] b   = new Byte[num];
                reader.GetBytes(0, 0, b, 0, b.Length);
                Response.ContentType = "Application/msword";
                //你把这一句换成相应类型即可
                Response.AddHeader("Content-Disposition", "attachment; filename=new.doc");
                Response.AddHeader("Content-Length", num.ToString());
                this.Response.Clear();
                System.IO.Stream fs = this.Response.OutputStream;
                fs.Write(b, 0, b.Length);
                fs.Close();
            }
            else
            {
                Page.RegisterClientScriptBlock("", "<script>alert('未获得文件信息!');location.href='Default.aspx'</script>");
            }
            reader.Close();
            conn.Close();
        }
        else
        {
            Page.RegisterClientScriptBlock("", "<script>alert('未获得文件的ID!');location.href='Default.aspx'</script>");
        }
    }
コード例 #8
0
        /// <summary>
        /// Loads the indicated profile into the class
        /// </summary>
        /// <param name="ProfileID">DBCode of the profile to load</param>
        /// <returns>True/False upon success or failure</returns>
        public bool LoadFromDB(int ProfileID)
        {
            this.ProfileID = ProfileID;

            using (OleDbConnection con = GPDatabaseUtils.Connect())
            {
                //
                // Build the command to read the blob to the database
                OleDbCommand cmd = new OleDbCommand("SELECT Profile FROM tblModelProfile WHERE DBCode = " + ProfileID, con);

                //
                // Execute the command
                try
                {
                    OleDbDataReader reader = cmd.ExecuteReader();
                    reader.Read();
                    //
                    // Pull the Training out
                    Byte[] blob = new Byte[(reader.GetBytes(0, 0, null, 0, int.MaxValue))];
                    reader.GetBytes(0, 0, blob, 0, blob.Length);
                    reader.Close();

                    using (MemoryStream ms = new MemoryStream())
                    {
                        ms.Write(blob, 0, blob.Length);
                        ms.Seek(0, SeekOrigin.Begin);
                        this.Load(ms);
                    }
                }
                catch (OleDbException)
                {
                    return(false);
                }
            }

            this.Name = GPDatabaseUtils.FieldValue(ProfileID, "tblModelProfile", "Name");

            return(true);
        }
コード例 #9
0
    // Return template data from an OleDbDataReader
    public TTemplate getTemplate(OleDbDataReader rs)
    {
        long readedBytes;

        tptBlob._size = 0;
        // alloc space
        System.Byte[] temp = new System.Byte[
            (int)GRConstants.GR_MAX_SIZE_TEMPLATE];
        // get bytes
        readedBytes = rs.GetBytes(1, 0, temp, 0, temp.Length);
        // copy to structure
        System.Array.Copy(temp, 0, tptBlob._tpt, 0, (int)readedBytes);
        // set real size
        tptBlob._size = (int)readedBytes;

        return(tptBlob);
    }
コード例 #10
0
ファイル: main.cs プロジェクト: staherianYMCA/test
        static int Main(string[] args)
        {
            int
                Result = -1;

            StreamWriter
                fstr_out = null;

            string
                tmpString = "log.log",
                TableName;

                        #if TEST_DB_BY_ODBC
            OdbcConnection
                odbc_conn = null;

            OdbcCommand
                odbc_cmd = null;

            OdbcDataReader
                odbc_rdr = null;

            OdbcDataAdapter
                odbc_da = null;
                        #endif

            OleDbConnection
                conn = null;

            OleDbCommand
                cmd = null;

            OleDbDataReader
                rdr = null;

            OleDbDataAdapter
                da = null;

            DataTable
                tmpDataTable;

            int
                tmpInt;

            object[]
            tmpObjects;

            FileStream
                fs;

            byte[]
            Blob;

            try
            {
                try
                {
                    fstr_out           = new StreamWriter(tmpString, false, System.Text.Encoding.GetEncoding(1251));
                    fstr_out.AutoFlush = true;

                    string
                        PathToDb               = "E:\\Soft.src\\CBuilder\\Tests\\Paradox\\Test.#1\\db",
                        CommonDbTableName      = "Common",
                        CommonDbTableSQLCreate = @"
create table " + CommonDbTableName + @"(
FInt integer,
FChar char(254)
)";

                                        #if TEST_DB_BY_ODBC
                    if (!PathToDb.EndsWith(Path.DirectorySeparatorChar.ToString()))
                    {
                        PathToDb += Path.DirectorySeparatorChar;
                    }

                    tmpString = "Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X;DefaultDir=" + PathToDb + ";Dbq=" + PathToDb + ";CollatingSequence=ASCII";
                    odbc_conn = new OdbcConnection(tmpString);
                    odbc_conn.Open();
                    fstr_out.WriteLine("ConnectionString: " + odbc_conn.ConnectionString);
                    fstr_out.WriteLine("ConnectionTimeout: " + odbc_conn.ConnectionTimeout.ToString());
                    fstr_out.WriteLine("Database: " + odbc_conn.Database);
                    fstr_out.WriteLine("DataSource: " + odbc_conn.DataSource);
                    fstr_out.WriteLine("Driver: " + odbc_conn.Driver);
                    fstr_out.WriteLine("ServerVersion: " + odbc_conn.ServerVersion);
                    fstr_out.WriteLine("State: " + odbc_conn.State.ToString());
                    fstr_out.WriteLine();

                    tmpString = PathToDb + CommonDbTableName + ".db";
                    if (File.Exists(tmpString))
                    {
                        File.Delete(tmpString);
                    }

                    odbc_cmd             = odbc_conn.CreateCommand();
                    odbc_cmd.CommandType = CommandType.Text;
                    odbc_cmd.CommandText = CommonDbTableSQLCreate;
                    odbc_cmd.ExecuteNonQuery();

                    odbc_cmd.CommandText = "insert into " + CommonDbTableName + " values (1,'FChar (‘„ар)')";
                    odbc_cmd.ExecuteNonQuery();

                                                #if TEST_BLOB
                    if (odbc_cmd == null)
                    {
                        odbc_cmd = odbc_conn.CreateCommand();
                    }
                    odbc_cmd.CommandType = CommandType.Text;

                    odbc_cmd.CommandText = "select * from TestTypes";
                    odbc_cmd.Parameters.Clear();
                    odbc_rdr = odbc_cmd.ExecuteReader();

                    do
                    {
                        if (odbc_rdr.HasRows)
                        {
                            for (int i = 0; i < odbc_rdr.FieldCount; ++i)
                            {
                                fstr_out.WriteLine(odbc_rdr.GetName(i) + " GetDataTypeName(): \"" + odbc_rdr.GetDataTypeName(i) + "\" GetFieldType(): \"" + odbc_rdr.GetFieldType(i) + "\"");
                            }

                            tmpInt = odbc_rdr.GetOrdinal("FGraphic");

                            while (odbc_rdr.Read())
                            {
                                tmpString = "FromBlob.bmp";
                                if (File.Exists(tmpString))
                                {
                                    File.Delete(tmpString);
                                }

                                Blob = (byte[])odbc_rdr["FGraphic"];
                                fs   = new FileStream(tmpString, FileMode.Create);
                                fs.Write(Blob, 0, Blob.Length);
                                fs.Close();

                                tmpString = "FromBlob_1.bmp";
                                if (File.Exists(tmpString))
                                {
                                    File.Delete(tmpString);
                                }

                                Blob = new byte[odbc_rdr.GetBytes(tmpInt, 0, null, 0, int.MaxValue)];
                                rdr.GetBytes(tmpInt, 0, Blob, 0, Blob.Length);
                                fs = new FileStream(tmpString, FileMode.Create);
                                fs.Write(Blob, 0, Blob.Length);
                                fs.Close();
                            }
                        }
                    }while(rdr.NextResult());
                    odbc_rdr.Close();
                                                #endif

                    odbc_conn.Close();
                                        #endif

                    if (PathToDb.EndsWith(Path.DirectorySeparatorChar.ToString()))
                    {
                        PathToDb = PathToDb.Remove(PathToDb.Length - 1, 1);
                    }

                    tmpString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + PathToDb + ";Extended Properties=Paradox 5.x";
                    conn      = new OleDbConnection(tmpString);
                    conn.Open();
                    fstr_out.WriteLine("ConnectionString: " + conn.ConnectionString);
                    fstr_out.WriteLine("ConnectionTimeout: " + conn.ConnectionTimeout.ToString());
                    fstr_out.WriteLine("Database: " + conn.Database);
                    fstr_out.WriteLine("DataSource: " + conn.DataSource);
                    fstr_out.WriteLine("Provider: " + conn.Provider);
                    fstr_out.WriteLine("ServerVersion: " + conn.ServerVersion);
                    fstr_out.WriteLine("State: " + conn.State.ToString());
                    fstr_out.WriteLine();

                    tmpString = PathToDb + Path.DirectorySeparatorChar + CommonDbTableName + ".db";
                    if (File.Exists(tmpString))
                    {
                        File.Delete(tmpString);
                    }

                    cmd             = conn.CreateCommand();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = CommonDbTableSQLCreate;
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "insert into " + CommonDbTableName + " values (1,'FChar (‘„ар)')";
                    cmd.ExecuteNonQuery();

                                        #if TEST_BLOB
                    if (cmd == null)
                    {
                        cmd = conn.CreateCommand();
                    }
                    cmd.CommandType = CommandType.Text;

                    TableName  = "TestTypes";
                    tmpObjects = new object[] { null, null, TableName, null };

                    fstr_out.WriteLine("OleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns)");
                    tmpDataTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, tmpObjects);
                    fstr_out.WriteLine("Columns in " + TableName + " table:");
                    foreach (DataRow row in tmpDataTable.Rows)
                    {
                        fstr_out.WriteLine("\t" + row["TABLE_CATALOG"] + " " + row["TABLE_NAME"] + " " + row["COLUMN_NAME"].ToString() + " " + row["DATA_TYPE"] + " " + row["TABLE_SCHEMA"]);
                    }
                    fstr_out.WriteLine();

                                                #if TEST_BLOB_SAVE
                    cmd.CommandText = "update TestTypes set FGraphic = ?";
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("FGraphic", OleDbType.LongVarBinary);
                    fs   = new FileStream("welcome.bmp", FileMode.Open, FileAccess.Read);
                    Blob = new byte[fs.Length];
                    fs.Read(Blob, 0, Blob.Length);
                    cmd.Parameters["FGraphic"].Value = Blob;
                    tmpInt = cmd.ExecuteNonQuery();
                                                #endif

                    cmd.CommandText = "select * from TestTypes";
                    cmd.Parameters.Clear();
                    rdr = cmd.ExecuteReader();

                    do
                    {
                        if (rdr.HasRows)
                        {
                            for (int i = 0; i < rdr.FieldCount; ++i)
                            {
                                fstr_out.WriteLine(rdr.GetName(i) + " GetDataTypeName(): \"" + rdr.GetDataTypeName(i) + "\" GetFieldType(): \"" + rdr.GetFieldType(i) + "\"");
                            }

                            tmpInt = rdr.GetOrdinal("FGraphic");

                            while (rdr.Read())
                            {
                                tmpString = "FromBlob.bmp";
                                if (File.Exists(tmpString))
                                {
                                    File.Delete(tmpString);
                                }

                                Blob = (byte[])rdr["FGraphic"];
                                fs   = new FileStream(tmpString, FileMode.Create);
                                fs.Write(Blob, 0, Blob.Length);
                                fs.Close();

                                tmpString = "FromBlob_1.bmp";
                                if (File.Exists(tmpString))
                                {
                                    File.Delete(tmpString);
                                }

                                Blob = new byte[rdr.GetBytes(tmpInt, 0, null, 0, int.MaxValue)];
                                rdr.GetBytes(tmpInt, 0, Blob, 0, Blob.Length);
                                fs = new FileStream(tmpString, FileMode.Create);
                                fs.Write(Blob, 0, Blob.Length);
                                fs.Close();
                            }
                        }
                    }while(rdr.NextResult());
                    rdr.Close();
                                        #endif

                    Result = 0;
                }
                catch (Exception eException)
                {
                    Console.WriteLine(eException.GetType().FullName + Environment.NewLine + "Message: " + eException.Message + Environment.NewLine + "StackTrace:" + Environment.NewLine + eException.StackTrace);
                }
            }
            finally
            {
                                #if TEST_DB_BY_ODBC
                if (odbc_rdr != null && !odbc_rdr.IsClosed)
                {
                    odbc_rdr.Close();
                }

                if (odbc_conn != null && odbc_conn.State == System.Data.ConnectionState.Open)
                {
                    odbc_conn.Close();
                }
                                #endif

                if (rdr != null && !rdr.IsClosed)
                {
                    rdr.Close();
                }

                if (conn != null && conn.State == System.Data.ConnectionState.Open)
                {
                    conn.Close();
                }

                if (fstr_out != null)
                {
                    fstr_out.Close();
                }
            }

            return(Result);
        }
コード例 #11
0
        /// <summary>
        /// Test CUBRID data types Get...()
        /// </summary>
        private static void Test_Various_DataTypes()
        {
            using (OleDbConnection conn = new OleDbConnection())
            {
                conn.ConnectionString = TestCasesOld.connString;
                conn.Open();

                TestCasesOld.ExecuteSQL("drop table if exists t", conn);

                string sql = "create table t(";
                sql += "c_integer_ai integer AUTO_INCREMENT, ";
                sql += "c_smallint smallint, ";
                sql += "c_integer integer, ";
                sql += "c_bigint bigint, ";
                sql += "c_numeric numeric(15,1), ";
                sql += "c_float float, ";
                sql += "c_decimal decimal(15,3), ";
                sql += "c_double double, ";
                sql += "c_char char, ";
                sql += "c_varchar varchar(4096), ";
                sql += "c_time time, ";
                sql += "c_date date, ";
                sql += "c_timestamp timestamp, ";
                sql += "c_datetime datetime, ";
                sql += "c_bit bit(1), ";
                sql += "c_varbit bit varying(4096), ";
                sql += "c_monetary monetary, ";
                sql += "c_string string";
                sql += ")";
                TestCasesOld.ExecuteSQL(sql, conn);

                sql  = "insert into t values(";
                sql += "1, ";
                sql += "11, ";
                sql += "111, ";
                sql += "1111, ";
                sql += "1.1, ";
                sql += "1.11, ";
                sql += "1.111, ";
                sql += "1.1111, ";
                sql += "'a', ";
                sql += "'abcdfghijk', ";
                sql += "TIME '13:15:45 pm', ";
                sql += "DATE '00-10-31', ";
                sql += "TIMESTAMP '13:15:45 10/31/2008', ";
                sql += "DATETIME '13:15:45 10/31/2008', ";
                sql += "B'0', ";
                sql += "B'0', ";
                sql += "123456789, ";
                sql += "'qwerty'";
                sql += ")";
                TestCasesOld.ExecuteSQL(sql, conn);

                sql = "select * from t";
                using (OleDbCommand cmd = new OleDbCommand(sql, conn))
                {
                    try
                    {
                        OleDbDataReader reader = cmd.ExecuteReader();
                        while (reader.Read()) //only one row will be available
                        {
                            Debug.Assert(reader.GetInt32(0) == 1);
                            Debug.Assert(reader.GetInt16(1) == 11);
                            Debug.Assert(reader.GetInt32(2) == 111);
                            Debug.Assert(reader.GetInt64(3) == 1111);
                            Debug.Assert(reader.GetDecimal(4) == (decimal)1.1);
                            Debug.Assert(reader.GetFloat(5) == (float)1.11); //"Single"
                            Debug.Assert(reader.GetDecimal(6) == (decimal)1.111);
                            Debug.Assert(reader.GetDouble(7) == (double)1.1111);

                            //We use GetString() because GetChar() is not supported or System.Data.OleDb.
                            //http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getchar
                            Debug.Assert(reader.GetString(8) == "a");          //"String" ("Char" in CUBRID)

                            Debug.Assert(reader.GetString(9) == "abcdfghijk"); //"String" ("String in CUBRID)

                            //GetGateTime cannot cast just the time value in a DateTime object, so we use TimeSpan
                            Debug.Assert(reader.GetTimeSpan(10) == new TimeSpan(13, 15, 45));               //"TimeSpan"

                            Debug.Assert(reader.GetDateTime(11) == new DateTime(2000, 10, 31));             //"DateTime"
                            Debug.Assert(reader.GetDateTime(12) == new DateTime(2008, 10, 31, 13, 15, 45)); //"DateTime"
                            Console.WriteLine(reader.GetValue(13));
                            Debug.Assert(reader.GetDateTime(13) == new DateTime(2008, 10, 31, 13, 15, 45)); //"DateTime"

                            //The GetByte() method does not perform any conversions and the driver does not give tha data as Byte
                            //http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getbyte
                            //Use GetValue() or GetBytes() methods to retrieve BIT coulumn value
                            //     Debug.Assert((reader.GetValue(14) as byte[])[0] == (byte)0); //"Byte[]" ("bit(1)" in CUBRID)
                            //Or
                            Byte[] value = new Byte[1];
                            reader.GetBytes(14, 0, value, 0, 1);

                            // Debug.Assert(value[0] == (byte)0);//"Byte[]" ("bit(1)" in CUBRID)
                            //Debug.Assert((reader.GetValue(14) as byte[])[0] == (byte)0); //"Byte[]" ("bit varying(4096)" in CUBRID)
                            //Or
                            //  reader.GetBytes(15, 0, value, 0, 1);
                            // Debug.Assert(value[0] == (byte)0);//"Byte[]" ("bit varying(4096)" in CUBRID)

                            Debug.Assert(reader.GetDouble(16) == 123456789.0); //"Double" ("Monetary" in CUBRID)
                            Debug.Assert(reader.GetString(17) == "qwerty");    //"String"
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                TestCasesOld.ExecuteSQL("drop table if exists t", conn);
            }
        }
コード例 #12
0
        static int Main(string[] args)
        {
            ErrorLevel errorLevel = ErrorLevel.Unknwon;

            try
            {
                if (args.Length < 2)
                {
                    Console.WriteLine(GetHelpString());
                    errorLevel = ErrorLevel.CommandLineSyntaxError;
                }
                else
                {
                    try
                    {
                        #region @parameters
                        string connectionString = args[0];
                        if (connectionString[0] == '@')
                        {
                            connectionString = ReadParameterFromFile(connectionString.Substring(1));
                        }

                        string sql = args[1];
                        if (sql[0] == '@')
                        {
                            sql = ReadParameterFromFile(sql.Substring(1));
                        }
                        #endregion


                        using (OleDbConnection oleDbConnection = new OleDbConnection(connectionString))
                        {
                            oleDbConnection.Open();
                            using (OleDbCommand oleDbCommand = new OleDbCommand(sql, oleDbConnection))
                            {
                                oleDbCommand.CommandType = System.Data.CommandType.Text;
                                using (OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader())
                                {
                                    const int bufferSize = 2014;

                                    byte[] buffer = new byte[bufferSize];

                                    long bytesRead;

                                    while (oleDbDataReader.Read())
                                    {
                                        using (FileStream stream = new FileStream(oleDbDataReader[0].ToString(), FileMode.Create))
                                        {
                                            Console.Write("Extracting " + oleDbDataReader[0].ToString() + "...");
                                            using (BinaryWriter writer = new BinaryWriter(stream))
                                            {
                                                bytesRead = oleDbDataReader.GetBytes(1, stream.Position, buffer, 0, bufferSize);
                                                while (bytesRead > 0)
                                                {
                                                    writer.Write(buffer, 0, (int)bytesRead);
                                                    bytesRead = oleDbDataReader.GetBytes(1, stream.Position, buffer, 0, bufferSize);
                                                }

                                                writer.Close();
                                                Console.WriteLine("Done");
                                            }
                                        }
                                    }
                                    errorLevel = ErrorLevel.OK;
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        errorLevel = ErrorLevel.Exception;
                        Console.WriteLine(GetHelpString());
                        Console.WriteLine(string.Empty);
                        Console.WriteLine("ERROR:" + exception.Message);
                    }
                }
            }
            catch
            {
                //We should have already caught everything.  This should at least allow the errorlevel to be reported OK.
            }
            return((int)errorLevel);
        }
コード例 #13
0
        public void DoTestTypes(DbTypeParametersCollection row)
        {
            testTypesInvocations++;
            exp = null;
            string          rowId = "43966_" + this.testTypesInvocations.ToString();
            OleDbConnection con   = null;
            OleDbDataReader rdr   = null;

            try
            {
                row.ExecuteInsert(rowId);
                row.ExecuteSelectReader(rowId, out rdr, out con);
                while (rdr.Read())
                {
                    //Run over all the columns in the result set row.
                    //For each column, try to read it as a byte array.
                    for (int i = 0; i < row.Count; i++)
                    {
                        if (row[i].Value.GetType() == typeof(byte[]))                         //The value in the result set should be a byte array.
                        {
                            try
                            {
                                BeginCase(string.Format("Calling GetBytes() on a field of dbtype {0}", row[i].DbTypeName));
                                byte[] origBytes = (byte[])row[i].Value;
                                byte[] retBytes  = new byte[origBytes.Length];
                                rdr.GetBytes(i, 0, retBytes, 0, origBytes.Length);
                                Compare(origBytes, retBytes);
                            }
                            catch (Exception ex)
                            {
                                exp = ex;
                            }
                            finally
                            {
                                EndCase(exp);
                                exp = null;
                            }
                        }
                        else                         //The value in the result set should NOT be byte array. In this case an Invalid case exception should be thrown.
                        {
                            try
                            {
                                BeginCase(string.Format("Calling GetBytes() on a field of dbtype {0}", row[i].DbTypeName));
                                byte[] retBytes = new byte[1];
                                rdr.GetBytes(i, 0, retBytes, 0, 1);
                                ExpectedExceptionNotCaught("InvalidCastException");
                            }
                            catch (InvalidCastException ex)
                            {
                                ExpectedExceptionCaught(ex);
                            }
                            catch (Exception ex)
                            {
                                exp = ex;
                            }
                            finally
                            {
                                EndCase(exp);
                                exp = null;
                            }
                        }
                    }
                }
            }
            finally
            {
                row.ExecuteDelete(rowId);
                if (rdr != null && !rdr.IsClosed)
                {
                    rdr.Close();
                }

                if (con != null && con.State != ConnectionState.Closed)
                {
                    con.Close();
                }
            }
        }