ExecuteReader() public method

public ExecuteReader ( ) : OleDbDataReader
return OleDbDataReader
コード例 #1
1
ファイル: Form5.cs プロジェクト: sankeerthsaan18/Dignostic
        private void lc(object sender, MouseEventArgs e)
        {
            c.Open();
            DataSet ds = new DataSet();
            string query = "select ID,pname,bill,pbill from pdetails where date=@bc ";
            OleDbCommand cmd = new OleDbCommand(query, c);
            cmd.Parameters.Add("@bc", OleDbType.Date).Value = dateTimePicker1.Value.Date;
            OleDbDataReader dr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dr);
            /*ds.Tables.Add(dt);
            OleDbDataAdapter da = new OleDbDataAdapter();
            da.Fill(dt);*/
            dataGridView1.DataSource = dt.DefaultView;
            c.Close();
            try
            {
                c.Open();
                String str = @"SELECT SUM(pbill) FROM pdetails WHERE date=@bb;";

                OleDbCommand comm2 = new OleDbCommand(str, c);
                comm2.Parameters.Add("@bb", OleDbType.Date).Value = dateTimePicker1.Value.Date;
                bill = Convert.ToDouble(comm2.ExecuteScalar());

                label3.Text = bill.ToString() + "/-";
            }
            catch(Exception ex)
            {
                MessageBox.Show("selected date miss match");
                c.Close();
            }
                c.Close();
        }
コード例 #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
            string sql = "";
         string connstring =@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\DropBox\My Dropbox\Devry\CIS407\SU10B\day8\mobileweb1\NorthWind.mdb;";
            System.Data.OleDb.OleDbDataReader dr;
            System.Data.OleDb.OleDbCommand comm = new System.Data.OleDb.OleDbCommand();

            //get this from connectionstrings.com/access
            conn.ConnectionString = connstring;
            conn.Open();
            //here I can talk to my db...
            comm.Connection = conn;

            //Console.WriteLine(conn.State);
            sql = "select categoryid, categoryname from categories";
            comm.CommandText = sql;
            dr = comm.ExecuteReader();
            rptCategory.DataSource = dr;
            rptCategory.DataBind();
            dr.Close();
            //Console.WriteLine(conn.State);
            sql = "select supplierid, companyname from suppliers";
            comm.CommandText = sql;
            dr = comm.ExecuteReader();
            rptSupplier.DataSource = dr;
            rptSupplier.DataBind();
    }
コード例 #3
0
        public void Select_TabelaControleDeVendaPessoa()
        {
            String _strSQL;

            _strSQL = "SELECT Código, Nome + Razao_Social FROM TabelaControleDeVendaPessoa Order by Nome + Razao_Social;";
            _OleDbCommand.CommandText = _strSQL;
            _DataReader = _OleDbCommand.ExecuteReader();
        }
コード例 #4
0
    protected void LoadData()
    {
        string strsql = "select * from customers where custnumber = " + Session["custid"];
        OleDbConnection myConn = new OleDbConnection();
        myConn.ConnectionString = System.Web.Configuration.WebConfigurationManager.
        ConnectionStrings["AcmeShoppeConnectionString"].ConnectionString;
        OleDbCommand myCmd = new OleDbCommand(strsql, myConn);
        OleDbDataReader myReader;
        if (myConn.State == ConnectionState.Closed) myConn.Open();
            myReader = myCmd.ExecuteReader();

            if (myReader.HasRows)
            {
                myReader.Read();
                this.lblFName.Text = myReader["FirstName"].ToString();
                this.lblLName.Text = myReader["LastName"].ToString();
                this.txtAddress.Text = myReader["Address"].ToString();
                this.txtCity.Text = myReader["City"].ToString();
                this.txtZip.Text = myReader["ZipCode"].ToString();
                this.DropDownList1.SelectedValue = myReader["State"].ToString();
            }
            else
                this.lblerr.Text = "error";
         myReader.Close();
         myCmd.CommandText = "select sum(extension) from cart_view01 " +
                                    "where cartnumber = " + Session["cartnumber"];
         decimal decSubtotal = 0;
         double decSalesTax = 0;
         double decTotal = 0;
         double decShip = 3.25;
         if (myConn.State == ConnectionState.Closed) myConn.Open();
         myReader = myCmd.ExecuteReader();
         if (myReader.HasRows)
         {
             myReader.Read();
             if (myReader[0] != DBNull.Value)
             {
                 decSubtotal = Convert.ToDecimal(myReader[0].ToString());
                 this.lblSubtotal.Text = decSubtotal.ToString("c");
             }
             decSalesTax = Convert.ToDouble(decSubtotal) * .05;
             Math.Round(decSalesTax, 2);
             decTotal = Convert.ToDouble(decSubtotal) + decSalesTax + decShip;
             Math.Round(decTotal, 2);
             this.lblTax.Text = decSalesTax.ToString("c");
             this.lblTotal.Text = decTotal.ToString("c");
             this.lblShipping.Text = decShip.ToString("c");
         }
         else
             this.lblerr.Text = "error";
         myConn.Close();
    }
コード例 #5
0
ファイル: Form1.cs プロジェクト: voyl/myprojects
        private void Guncelle()
        {
            using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=hesap.mdb"))
            {
                conn.Open();
                OleDbCommand komut = new OleDbCommand();
                komut.Connection = conn;
                komut.CommandText = "Select * from hesap"; // sorgu / komut cumlemi yazıyorum.
                komut.ExecuteNonQuery(); // insert , updateiçin gerekli satir sayisi donduruyoruz.
                OleDbDataReader dr = komut.ExecuteReader(); // datareader olusturup komut sorgulayıp veritabaninda okuma işlemini tanıtıyoruz
                while (dr.Read()) // datareader ile okuyoruz.
                {
                    string hadi = dr["hadi"].ToString();
                    string kadi = dr["kadi"].ToString();
                    string q;
                    using (WebClient asd = new WebClient())
                    {
                        asd.Encoding = Encoding.UTF8;
                        q = asd.DownloadString("http://gdata.youtube.com/feeds/api/users/" + kadi + "/uploads?v=2&alt=jsonc&max-results=0");
                    }
                    string[] adet1 = q.Split(new string[] { "totalItems\":" }, StringSplitOptions.None);
                    string[] adet2 = adet1[1].Split(',');
                    listView1.Items.Add(new ListViewItem(new string[] { hadi, "Adet: "+adet2[0] }));
                }
                dr.Close();
                komut.ExecuteNonQuery(); // insert , updateiçin gerekli satir sayisi donduruyoruz.
                dr = komut.ExecuteReader(); // datareader olusturup komut sorgulayıp veritabaninda okuma işlemini tanıtıyoruz
                while (dr.Read()) // datareader ile okuyoruz.
                {
                    string kadi = dr["hadi"].ToString(); // veritabanimdaki "kadi" alanımdaki veriyi alip kadi değişkenine atıyorum(yukarıda string olusturmustum)
                    string sifre = dr["hsifresi"].ToString(); // aynı durum söz konusu
                    string devkey = dr["devkey"].ToString();
                    Random a = new Random();
                    string id = a.Next(100000, 999999).ToString();
                    YouTubeRequestSettings settings = new YouTubeRequestSettings(id, devkey, kadi,sifre);
                    YouTubeRequest request = new YouTubeRequest(settings);

                    string feedUrl = "https://gdata.youtube.com/feeds/api/users/default/uploads";

                    Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
                    foreach (Video entry in videoFeed.Entries)
                    {
                        string vid_thumb ="http://img.youtube.com/vi/"+entry.VideoId+"/0.jpg";
                        int izlenme = entry.ViewCount;
                        if(izlenme == -1)
                            izlenme = 0;
                        listView1.Items.Add(new ListViewItem(new string[] { kadi,entry.YouTubeEntry.Title.Text,izlenme.ToString()  }));
                    }
                }
            }
        }
コード例 #6
0
ファイル: Database.cs プロジェクト: baskinbrent/battleship
        public static Dictionary<string, Dictionary<string, object>> GetStatistics()
        {
            Dictionary<string, Dictionary<string, object>> list = new Dictionary<string, Dictionary<string, object>>();

            string strConnection = "provider=Microsoft.ACE.OLEDB.12.0;Data Source=Battleship.accdb;";
            string strSQL = "";
            OleDbConnection myConnection = new OleDbConnection(strConnection);
            OleDbCommand myCommand = new OleDbCommand(strSQL, myConnection);
            try
            {
                myConnection.Open();
                strSQL = "SELECT Name, Min(Turns), Count(*) FROM Statistic WHERE IsWinner GROUP BY Name ORDER BY Name";
                myCommand.CommandText = strSQL;
                myCommand.CommandType = System.Data.CommandType.Text;
                OleDbDataReader reader = myCommand.ExecuteReader();
                while (reader.Read())
                {
                    Dictionary<string, object> fields = new Dictionary<string, object>();
                    fields["Turns"] = reader.GetInt32(1).ToString();
                    fields["Wins"] = reader.GetInt32(2).ToString();
                    fields["Loses"] = 0;
                    list[reader.GetString(0)] = fields;
                }
                reader.Close();

                strSQL = "SELECT Name, Count(*) FROM Statistic WHERE NOT IsWinner GROUP BY Name ORDER BY Name";
                myCommand.CommandText = strSQL;
                myCommand.CommandType = System.Data.CommandType.Text;
                reader = myCommand.ExecuteReader();
                while (reader.Read())
                {
                    if (!list.ContainsKey(reader.GetString(0)))
                    {
                        Dictionary<string, object> fields = new Dictionary<string, object>();
                        fields["Turns"] = "DNA";
                        fields["Wins"] = 0;
                        list[reader.GetString(0)] = fields;
                    }
                    list[reader.GetString(0)]["Loses"] = reader.GetInt32(1).ToString();
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
            myConnection.Close();
            return list;
        }
コード例 #7
0
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        string strsql = "select [CustNumber], [Email], [PWD] from customers";
        OleDbConnection myConn = new OleDbConnection();
        myConn.ConnectionString = System.Web.Configuration.WebConfigurationManager.
        ConnectionStrings["AcmeShoppeConnectionString"].ConnectionString;
        OleDbCommand myCmd = new OleDbCommand(strsql, myConn);
        OleDbDataReader myReader;
        if (myConn.State == ConnectionState.Closed) myConn.Open();
            myReader = myCmd.ExecuteReader();
            DataTable dataTable = new DataTable();
            dataTable.Load(myReader);
            int rowCount = rowCount = dataTable.Rows.Count;
            myReader = myCmd.ExecuteReader();

            int i = 0;

            if (myReader.HasRows)
            {

                while (i < rowCount)
                {
                    myReader.Read();

                    string strId = this.txtUser.Text;
                    string strPwd = this.txtPass.Text;
                    string memId = myReader["Email"].ToString();
                    string memPwd = myReader["PWD"].ToString();
                    if (strId == memId && strPwd == memPwd)
                    {
                        FormsAuthentication.RedirectFromLoginPage(strId, false, strPwd);
                        string custid = myReader["CustNumber"].ToString();
                        Session["custid"] = custid;
                        Session["userid"] = memId;
                        break;

                    }
                    else if (strId == "admin" && strPwd == "admin")
                    {
                        FormsAuthentication.RedirectFromLoginPage(strId, false, strPwd);
                        break;
                    }

                    i++;
                }
                if (i == rowCount)
                        this.lblmessage.Text = "User Does not exist!";
            }
    }
コード例 #8
0
        private void button1_Click(object sender, EventArgs e)
        {
            var Database = new OleDiBi.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Медведев.mdb");

            Database.Open();
            OleDiBi.OleDbCommand    loadingOfTable = new OleDiBi.OleDbCommand(richTextBox1.Text, Database);
            OleDiBi.OleDbDataReader result         = loadingOfTable.ExecuteReader();
            DataTable table = new DataTable();

            for (int i = 0; i < result.FieldCount; i++)
            {
                table.Columns.Add(result.GetName(i));
            }

            while (result.Read() == true)
            {
                object[] yacheiki = new object[result.FieldCount];
                for (int i = 0; i < result.FieldCount; i++)
                {
                    yacheiki[i] = result.GetValue(i);
                }
                table.Rows.Add(yacheiki);
            }
            result.Close();
            Database.Close();

            dataGridView1.DataSource = table;
        }
コード例 #9
0
        // column1 column2 column3
        // ****    ***     *****
        //  **              ***
        // If inserting into column 2, we are inserting into an existing row
        // if inserting into column 1 or 3, we are creating a new row
        private bool ShouldInsertIntoNewRow(OleDb.OleDbConnection conn, string columnName)
        {
            OleDb.OleDbCommand command = new OleDb.OleDbCommand();
            command.Connection  = conn;
            command.CommandText = "SELECT TOP 1 * FROM `Sheet1$` WHERE `" + columnName + "` IS NULL";
            int ct = 0;

            try
            {
                OleDb.OleDbDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    ct++;
                }

                reader.Close();
            } catch (OleDb.OleDbException)
            {
                Forms.MessageBox.Show(Strings.error, Strings.errorCaption);
            }

            if (ct > 0)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
コード例 #10
0
ファイル: Disciplines.cs プロジェクト: Uselessness13/Labs
        private void Disciplines_Load(object sender, EventArgs e)
        {
            //dataGridView1.DataSource = MainForm.FunctionOfAdding(nameoftable);

            var data1 = new List <Dvapolya>();

            Date_baseone = new dabse.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Медведев.mdb");
            Date_baseone.Open();
            dabse.OleDbCommand    com1      = new dabse.OleDbCommand("Select Название, Шифр FROM Специальности", Date_baseone);
            dabse.OleDbDataReader resulter1 = com1.ExecuteReader();

            while (resulter1.Read() == true)
            {
                var mc = new Dvapolya
                {
                    secondpole = resulter1[0].ToString().Trim(),
                    firstpole  = resulter1[1].ToString().Trim()
                };
                data1.Add(mc);
            }

            comboBox1.DataSource    = data1;
            comboBox1.DisplayMember = "secondpole";
            comboBox1.ValueMember   = "firstpole";
        }
コード例 #11
0
        /// <summary>
        /// 执行SQL语句 返回reader
        /// </summary>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public OleDbDataReader ExecuteReaderSql(string SQLString)
        {
            System.Data.OleDb.OleDbCommand Cmd = new System.Data.OleDb.OleDbCommand();
            Cmd.Connection = _Con;
            string sql = "";

            try
            {
                if (_sTrAccessPath == "")
                {
                    sql = SQLString.Replace("#", "'");//如果是SQL数据库则需要将#替换为'
                }
                else
                {
                    sql = SQLString;
                }
                Cmd.CommandText = sql;
                _Reader         = Cmd.ExecuteReader();
                Cmd             = null;
                return(_Reader);
            }
            catch (OleDbException e)
            {
                CLDC_DataCore.Const.GlobalUnit.Logger.Fatal("向数据库插入数据失败:" + sql, e);
                return(null);
            }
            catch (Exception ex)
            {
                CLDC_DataCore.Const.GlobalUnit.Logger.Fatal("向数据库插入数据失败:", ex);
                return(null);
            }
        }
コード例 #12
0
        public String[] SutunAdlari(String cmdSorgu)
        {
            String[] dizi = null;
            try
            {
                Kontrol();
                cmd  = new OleDbCommand(cmdSorgu, bglnti);
                dR   = cmd.ExecuteReader();
                dizi = new String[dR.FieldCount];
                for (int i = 0; i < dR.FieldCount; i++)
                {
                    dizi[i] = dR.GetName(i);
                }

                dR.Close();
                dR.Dispose();
                cmd.Dispose();
            }
            catch (OleDbException ole)
            {
                MessageBox.Show(ole.Message);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally { bglnti.Close(); }
            return(dizi);
        }
コード例 #13
0
 /// <summary>取得OleDbDataReader</summary>
 /// <param name="strSQL">SQL 指令</param>
 /// <param name="oleDbConn">連線物件(OleDbConnection)</param>
 /// <returns>OleDbDataReader</returns>
 /// <remarks></remarks>
 public static OleDbDataReader getOleDbDataReader(string strSQL, System.Data.OleDb.OleDbConnection oleDbConn)
 {
     System.Data.OleDb.OleDbDataReader dr  = null;
     System.Data.OleDb.OleDbCommand    cmd = null;
     try
     {
         if (oleDbConn == null)
         {
             oleDbConn = createOleDbConnection();
         }
         if (!(oleDbConn.State == ConnectionState.Open))
         {
             oleDbConn.Open();
         }
         cmd = new System.Data.OleDb.OleDbCommand(strSQL, oleDbConn);
         dr  = cmd.ExecuteReader(CommandBehavior.CloseConnection);
     }
     catch (Exception Ex)
     {
         //Message.alertMessage("C0001", null, Ex.Message.ToString(), null);
         if (!(oleDbConn.State == ConnectionState.Closed))
         {
             oleDbConn.Close();
         }
         dr = null;
     }
     return(dr);
 }
コード例 #14
0
        } // end method FrmATM_Load

        // invoke when user provides account number
        private void RetrieveAccountInformation()
        {
            // specify account number of row from which data
            // will be retrieved
            objSelectAccountData.Parameters["AccountNumber"].Value =
                cboAccountNumbers.SelectedItem;

            objOleDbConnection.Open(); // open database connection

            // create database reader to read information from database
            OleDbDataReader objReader =
                objSelectAccountData.ExecuteReader();

            objReader.Read(); // open data reader connection

            // retrieve PIN number, balance amount and first name
            // information from database
            m_strPIN = Convert.ToString(
                objReader["PIN"]);
            m_decBalance = Convert.ToDecimal(
                objReader["BalanceAmount"]);
            m_strFirstName = Convert.ToString(
                objReader["FirstName"]);

            objReader.Close();          // close data reader connection
            objOleDbConnection.Close(); // close database connection
        } // end method RetrieveAccountInformation
コード例 #15
0
ファイル: Security.cs プロジェクト: edcrane-gsa/Ed-Crane-GSA
        }     //end of method

        //This method is used to verify that user is a
        //part of Lotus Notes- table (m:\ccmail\maildir.dbf)
        //7/17/2003 - Madan - Pointing the table to Oracle - VITAP.world
        //Input parameter UserName = First Name Initial, LastName
        //public static bool IsLotusNotesUser(string firstName, string lastName, System.Data.OracleClient.OracleConnection App_Connection) {
        //    string Message = "";
        //    string UserName1 = firstName.Trim().ToUpper() + " " + lastName.Trim().ToUpper();
        //    string UserName2 = lastName.Trim().ToUpper() + ", " + firstName.Trim().ToUpper();
        //    try {
        //        System.Data.OracleClient.OracleCommand CmdLotusMail = new System.Data.OracleClient.OracleCommand();
        //        CmdLotusMail.CommandText = "SELECT Notesname from maildir WHERE Notesname = '" + Utilities.SqlEncode(UserName1.ToUpper().Trim()) + "' or upper(Name) ='" + Utilities.SqlEncode(UserName2) + "'";
        //        CmdLotusMail.Connection = App_Connection;  //ConnLotusMail;
        //        if (App_Connection.State != System.Data.ConnectionState.Open) {
        //            CmdLotusMail.Connection.Open();
        //        }
        //        System.Data.OracleClient.OracleDataReader myReader = CmdLotusMail.ExecuteReader();
        //        if (myReader.Read()) {
        //            Message = myReader["Notesname"].ToString().Trim();
        //        }
        //        myReader.Close();
        //        CmdLotusMail.Connection.Close();
        //    }
        //    catch (System.Exception ex) { // if exception occurs, make an entry in the server event log
        //        EventLog.AddWebErrors("GSA.R7BD.Utility", "Security", "IsLutusNotesUser", ex.Message);

        //    }
        //    if (Message != "") {
        //        return true;
        //    }
        //    else {
        //        return false;
        //    }
        //}  //end of this method


        //This method finds out if the user is a valid one in -- Users table at m:\oitems
        public static bool IsValidUser(string firstName, string lastName)
        {
            string Result = "";

            try {
                System.Data.OleDb.OleDbConnection ConnUser = new System.Data.OleDb.OleDbConnection();
                System.Data.OleDb.OleDbCommand    CmdUser  = new System.Data.OleDb.OleDbCommand();
                ConnUser.ConnectionString = ConnectionString.CSUsersTables();
                CmdUser.CommandText       = Queries.getValidUser(firstName, lastName);
                CmdUser.Connection        = ConnUser;
                CmdUser.Connection.Open();
                OleDbDataReader myReader = CmdUser.ExecuteReader();
                if (myReader.Read())
                {
                    Result = myReader["fname"].ToString().Trim();
                }
                myReader.Close();
                CmdUser.Connection.Close();
            }
            catch (System.Exception ex) {
                Console.Write(ex.Message + " " + ex.Source);
            }
            if (Result != "")
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }  //end of this method
コード例 #16
0
        public string monitor(string dev)
        {
            string val = "no";

            ExcelCon = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filename + "';Extended Properties=Excel 8.0;");
            ExcelCon.Close();
            ExcelCon.Open();
            try
            {
                System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
                cmd.Connection = ExcelCon;
                string date1 = DateTime.Parse("01/01/2015 " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + "").ToString("dd/MM/yyyy HH:mm:ss"); //DateTime.Now.ToString("dd/MM/yyyy HH:mm");
                string date2 = DateTime.Parse("01/01/2016 " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + "").ToString("dd/MM/yyyy HH:mm:ss"); //DateTime.Now.ToString("dd/MM/yyyy HH:mm");
                // string SQL = " select [" + dev + "] FROM [" + Title + "] WHERE [RecDateTime] =(SELECT min([RecDateTime]) FROM [" + Title + "] WHERE [RecDateTime] BETWEEN @p1 AND @p2)";

                string SQL = " select [" + dev + "] FROM [" + Title + "] WHERE [RecDateTime] =(SELECT min([RecDateTime]) FROM [" + Title + "] WHERE [RecDateTime] BETWEEN @p1 AND @p2)";
                cmd.CommandText = SQL;
                cmd.Parameters.Add("@p1", OleDbType.Date).Value = date1;
                cmd.Parameters.Add("@p2", OleDbType.Date).Value = date2;

                OleDbDataReader DR = cmd.ExecuteReader();
                DR.Read();
                val = DR.GetValue(0).ToString();
                // val = cmd.ExecuteScalar().ToString();
            }
            catch { }
            ExcelCon.Close();
            return(val);
        }
コード例 #17
0
ファイル: Security.cs プロジェクト: edcrane-gsa/Ed-Crane-GSA
        }//end of method

        // Addded by Madan on 02/21/2003 For Letting the website pull another page is Pegasys is down.
        public static string CheckApplicationStatus(String WebsiteName)
        {
            string strMemo = "Pegasys is Down";

            try {
                System.Data.OleDb.OleDbConnection ConnWeb = new System.Data.OleDb.OleDbConnection();
                System.Data.OleDb.OleDbCommand    CmdWeb  = new System.Data.OleDb.OleDbCommand();
                ConnWeb.ConnectionString = ConnectionString.CSforPasswordsTable();
                CmdWeb.CommandText       = Queries.getWebsiteSite(WebsiteName);
                CmdWeb.Connection        = ConnWeb;
                CmdWeb.Connection.Open();
                OleDbDataReader myReader = CmdWeb.ExecuteReader();
                if (myReader.Read())
                {
                    string strTerm = myReader["Term"].ToString().Trim();
                    if (strTerm == "True")
                    {
                        strMemo = myReader["Message"].ToString().Trim();
                    }
                    else   // if termimnate is false, means everything is ok, send empty string.
                    {
                        strMemo = "";
                    }
                }
                else
                {
                    strMemo = "";
                }
            }
            catch (System.Exception ex) {
                Console.Write(ex.Message);
            }
            return(strMemo);
        }       //end of method
コード例 #18
0
        private static Boolean IsMember(string TeamName, string Type)
        {
            Boolean blnReturn = false; // Intialize False

            //Get Current user
            Sage.SalesLogix.Security.SLXUserService usersvc     = (Sage.SalesLogix.Security.SLXUserService)Sage.Platform.Application.ApplicationContext.Current.Services.Get <Sage.Platform.Security.IUserService>();
            Sage.Entity.Interfaces.IUser            currentuser = usersvc.GetUser();
            // get the DataService to get a connection string to the database
            string SQL = "";

            SQL  = "select accessid from secrights where seccodeid = ";
            SQL += " (select seccodeid from seccode where (seccodedesc = '" + TeamName + "') ";
            SQL += " and (seccodetype = '" + Type + "')) and (accessid = '" + currentuser.Id.ToString() + "')";

            Sage.Platform.Data.IDataService datasvc = Sage.Platform.Application.ApplicationContext.Current.Services.Get <Sage.Platform.Data.IDataService>();
            using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(datasvc.GetConnectionString()))
            {
                conn.Open();
                using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(SQL, conn))
                {
                    OleDbDataReader reader = cmd.ExecuteReader();
                    //loop through the reader
                    while (reader.Read())
                    {
                        if (reader["accessid"].ToString() != string.Empty)
                        {
                            blnReturn = true;
                        }
                    }
                    reader.Close();
                }
            }
            return(blnReturn);
        }
コード例 #19
0
        private void button1_Click(object sender, EventArgs e)
        {
            string a = Convert.ToString(textBox1.Text);
            string b = Convert.ToString(textBox2.Text);

            string queryString = "SELECT * FROM [Admin]";
            string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Vladislav\Documents\kursach1.mdb";
            OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
            OleDbCommand myOleDbCommand = new OleDbCommand(queryString, myOleDbConnection);
            myOleDbConnection.Open();
            OleDbDataReader myOleDbDataReader = myOleDbCommand.ExecuteReader();


            while (myOleDbDataReader.Read())
            {
                if (myOleDbDataReader.GetString(0) == a && myOleDbDataReader.GetString(1) == b)
                {
                    Form6 form6 = new Form6();
                    form6.Visible = true;
                    this.Visible = false;
                    break;
                }

            }
            myOleDbDataReader.Close();
            myOleDbConnection.Close();
        }
コード例 #20
0
        public void NapolniForma()
        {
            String komanda = "EXECUTE spPodatociFirma";

            OleDbConnection OleCn = new System.Data.OleDb.OleDbConnection(konekcija);
            OleDbCommand    OleCm = new System.Data.OleDb.OleDbCommand(komanda, OleCn);
            OleDbDataReader dt;

            OleCm.Parameters.Add(new OleDbParameter("@Firma", vnesiTexBox.Text.Trim()));

            try
            {
                OleCn.Open();
                dt = OleCm.ExecuteReader();
                if (dt.Read())
                {
                    contaktLbl.Text = dt["Contact"].ToString();
                    telLbl.Text     = dt["Tel"].ToString();
                    faxLbl.Text     = dt["Fax"].ToString();
                    emailLbl.Text   = dt["Email"].ToString();
                    cityLbl.Text    = dt["City"].ToString();
                    countryLbl.Text = dt["Country"].ToString();
                    Sifra_Firma     = dt["Sifra_Firma"].ToString();
                }
            }
            catch (Exception ex)
            {
                OleCn.Close();
                MessageBox.Show(ex.Message);
            }
        }
コード例 #21
0
ファイル: myInfo.aspx.cs プロジェクト: waxiga/TypeMatch
    public void binderStudentInfo(string username)
    {
        try
        {
            OleDbConnection con=DB.createcon();
            OleDbCommand cmd=new OleDbCommand();
            cmd.CommandText="select * from [student] where [studentUsername]='"+username+"'";
            cmd.Connection=con;
            con.Open();
            OleDbDataReader odr= cmd.ExecuteReader();
            while(odr.Read()){
               this.userName.Text=username;
                this.student_name.Value=odr["studentName"].ToString();
                //this.student_id.Value = odr["studentID"].ToString();
                //this.student_xibie.Value = odr["studentDepartment"].ToString();
               // this.student_grate.Value = odr["studentGrade"].ToString();
                //this.student_class.Value = odr["studentClass"].ToString();
                //this.tel.Value = odr["studentTel"].ToString();
                this.qq.Value = odr["studentQQ"].ToString();
                this.about.Value = odr["studentAbout"].ToString();

                ////this.ChTypeTrainCount.Text=odr["trainChCount"].ToString();
                //this.EnTypeTrainCount.Text=odr["trainEnCount"].ToString();
                //this.ChypeMatchCount.Text=odr["mathchChCount"].ToString();
                //this.EnTypeMatchCount.Text=odr["mathchEnCount"].ToString();
            }
            odr.Close();
            con.Close();
        }
        catch (Exception exp)
        {
            saveErrorMessage.writeFile("查询学生的个人信息时出错",exp.ToString());
        }
    }
コード例 #22
0
 public IDataReader ExecuteDataReader(string connectionString, string query)
 {
     _connection = new OleDbConnection(connectionString);
     _connection.Open();
     var command = new OleDbCommand(query, _connection);
     return command.ExecuteReader();
 }
コード例 #23
0
ファイル: DataBindingY.aspx.cs プロジェクト: samuellin124/cms
        protected void Page_Load(object sender, System.EventArgs e)
        {
            // resolve the address to the Access database
            string fileNameString = this.MapPath(".");
            fileNameString += "..\\..\\..\\..\\data\\chartdata.mdb";

            // initialize a connection string
            string myConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileNameString;

            // define the database query
            string mySelectQuery="SELECT GrossSales FROM SALES WHERE QuarterEnding < #01/01/2002#;";

            // create a database connection object using the connection string
            OleDbConnection myConnection = new OleDbConnection(myConnectionString);

            // create a database command on the connection using query
            OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);

            // open the connection
            myCommand.Connection.Open();

            // create a database reader
            OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

            // since the reader implements and IEnumerable, pass the reader directly into
            // the DataBind method with the name of the Column selected in the query
            Chart1.Series["Default"].Points.DataBindY(myReader, "GrossSales");

            // close the reader and the connection
            myReader.Close();
            myConnection.Close();
        }
コード例 #24
0
ファイル: frmProfil.cs プロジェクト: Freakzor9/vikingii
        private void frmProfil_Load(object sender, EventArgs e)
        {
            OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data source=" + cale + "\\Soft.accdb");
            con.Open();
            string text = "select* from Utilizatori where Mail=@mail";//

            OleDbCommand com = new OleDbCommand(text, con);
            com.Parameters.AddWithValue("Mail", ((Main)this.MdiParent).nume);
            OleDbDataReader r = com.ExecuteReader();
            while (r.Read())
            {
                //if(System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                //{
                //    lblPic.ImageLocation = ((Main)this.MdiParent).url + "/img/"+;
                //}
                //else
                //{
                if (r["Imagine"].ToString() != "")
                {
                    lblPic.Image = System.Drawing.Image.FromFile(cale + r["Imagine"].ToString());
                }
                // }
                label2.Text = r["Nume"].ToString();
                label7.Text = r["Mail"].ToString();
                label8.Text = r["Clasa"].ToString();
                label9.Text = r["Acces"].ToString();
                label10.Text = r["Gen"].ToString();
            }
            r.Close();
            con.Close();
            note();
        }
コード例 #25
0
        public static void readFromDB(OleDbConnection conn)
        {
            string testSelect = " SELECT * FROM ImportAccess";
            OleDbCommand comm = new OleDbCommand(testSelect, conn);
            OleDbDataReader dr = comm.ExecuteReader();
            object[] buffer = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            StringBuilder sb = new StringBuilder();
            while (dr.Read())// populate buffer with values from db
            {
                int value = dr.GetValues(buffer);

                for (int i = 0; i < buffer.Length; i++)
                {
                    sb.Append(buffer[i] + ",");
                }
                sb.Remove(buffer.Length - 1, 1);
            }
            ConsoleKeyInfo cki = new ConsoleKeyInfo();
            while (true)    // keep console window open
            {
                Console.WriteLine("Returned values " + sb.ToString());
                cki = Console.ReadKey(true);
                if (cki.Key == ConsoleKey.X)
                {
                    break;
                }
            }
            dr.Close();
        }
コード例 #26
0
	private void LoadItems()
	{
		string query = "";
		
		OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("../App_Data/items.mdb"));
		myConn.Open();

		for (int index = 0; index <= 24; index ++)
		{
			query = "update Items set Items = rnd() * 10 where Id = " + index.ToString();
			
			OleDbCommand myComm1 = new OleDbCommand(query, myConn);
			
			myComm1.ExecuteNonQuery();
			
			
			query = "update Items set Price = rnd() * 100 where Id = " + index.ToString();
			
			OleDbCommand myComm2 = new OleDbCommand(query, myConn);
			
			myComm2.ExecuteNonQuery();
		}
				
		query = "SELECT Id, Name, Items, Price FROM Items";
		OleDbCommand myComm = new OleDbCommand(query, myConn);
		OleDbDataReader myReader = myComm.ExecuteReader();
		
		gridItems.DataSource = myReader;
		gridItems.DataBind();
	
		myReader.Close();		
	}
コード例 #27
0
        public static DataTable FunctionOfAdding(String stringsione)
        {
            var Database = new dabse.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Медведев.mdb");

            Database.Open();
            dabse.OleDbCommand    loadingOfTable = new dabse.OleDbCommand("Select * From " + stringsione, Database);
            dabse.OleDbDataReader result         = loadingOfTable.ExecuteReader();
            DataTable             table          = new DataTable();

            for (int i = 0; i < result.FieldCount; i++)
            {
                table.Columns.Add(result.GetName(i));
            }

            while (result.Read() == true)
            {
                object[] yacheiki = new object[result.FieldCount];
                for (int i = 0; i < result.FieldCount; i++)
                {
                    yacheiki[i] = result.GetValue(i);
                }
                table.Rows.Add(yacheiki);
            }
            result.Close();
            Database.Close();
            return(table);
        }
コード例 #28
0
ファイル: Form1.cs プロジェクト: Veizdem/dotnet_labs
        public Form1()
        {
            InitializeComponent();

            var connection = new oleDB.OleDbConnection("Data Source=\"e:\\vic.mdb\";User ID=Admin;Provider=\"Microsoft.Jet.OLEDB.4.0\";");

            connection.Open();

            oleDB.OleDbCommand command = new oleDB.OleDbCommand("Select * From [Phones]", connection);

            oleDB.OleDbDataReader reader = command.ExecuteReader();

            DataTable table = new DataTable();

            table.Columns.Add(reader.GetName(0));
            table.Columns.Add(reader.GetName(1));
            table.Columns.Add(reader.GetName(2));

            while (reader.Read() == true)
            {
                table.Rows.Add(new object[] { reader.GetValue(0), reader.GetValue(1), reader.GetValue(2) });
            }

            reader.Close();
            connection.Close();

            dataGridView1.DataSource = table;
        }
コード例 #29
0
ファイル: PackAgeModel.cs プロジェクト: SHACHAR2/Every4Rent
        internal DataTable userDetail(string email)
        {
            System.Data.OleDb.OleDbCommand comm = new System.Data.OleDb.OleDbCommand();
            comm.CommandType = System.Data.CommandType.Text;
            comm.CommandText = "SELECT * FROM USERS WHERE [Email] = \'" + email + ";";
            comm.Connection  = conn;
            conn.Open();
            DataTable result = new DataTable();;

            try
            {
                //comm.Connection.Open();
                OleDbDataReader dr = comm.ExecuteReader();
                result.Load(dr);
                return(result);
                //MessageBox.Show((string)returnValue);
            }
            catch (Exception e)
            {
                conn.Close();
                MessageBox.Show(e.Message);
                return(null);
            }

            //throw new NotImplementedException();
        }
コード例 #30
0
        private void get_device_details()
        {
            try
            {
                string  SQL  = " select [title],[id],[building_id],[pin_id],[gateway_id],[type],[model],[serial],[manufacturer],[description] FROM [" + Title2 + "] WHERE id=@Id ";
                DataSet room = new DataSet();
                using (System.Data.OleDb.OleDbConnection ExcelCon = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filename + "';Extended Properties=Excel 8.0;"))
                {
                    ExcelCon.Open();

                    using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(SQL, ExcelCon))
                    {
                        cmd.CommandText = SQL;
                        cmd.Parameters.AddWithValue("@Id", Request.QueryString["Id"]);
                        using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
                        {
                            adapter.Fill(room);
                        }
                        OleDbDataReader EDR = cmd.ExecuteReader();
                        EDR.Read();
                        string code = EDR.GetValue(0).ToString() + "(" + EDR.GetValue(1).ToString() + "/" + EDR.GetValue(2).ToString() + ":" + EDR.GetValue(3).ToString() + "/" + EDR.GetValue(4).ToString() + ")";
                        Session["Dev_ExcelTitle"] = code;
                    }

                    ExcelCon.Close();
                }
                GridView1.DataSource = room;
                GridView1.DataBind();
            }
            catch { Response.Redirect("~/Default.aspx"); }
        }
コード例 #31
0
ファイル: ImportAccess.cs プロジェクト: c1982/mpimport
        public override List<DomainAlias> GetDomainAliases(string domainName)
        {
            var _tmp = new List<DomainAlias>();

            using (OleDbConnection _conn = new OleDbConnection(Settings.Default.connectionString))
            {
                _conn.Open();
                using (OleDbCommand _cmd = new OleDbCommand(@"SELECT domain_aliases.name AS alias, domains.name AS [domain], domain_aliases.status
                                                                FROM (domain_aliases INNER JOIN
                                                            domains ON domain_aliases.dom_id = domains.id)
                                                                WHERE (domain_aliases.status = 0) AND (domains.name = ?)", _conn))
                {
                    _cmd.CommandType = CommandType.Text;
                    _cmd.Parameters.AddWithValue("NAME", domainName);

                    using (OleDbDataReader _read = _cmd.ExecuteReader())
                    {
                        while (_read.Read())
                        {
                            var _d = new DomainAlias();
                            _d.Domain = _read["domain"].ToString();
                            _d.Alias = _read["alias"].ToString();

                            _tmp.Add(_d);
                        }
                    }
                }
                _conn.Close();
            }

            return _tmp;
        }
コード例 #32
0
        public void NapolniForma()
        {
            String komanda = "EXECUTE spPodatociProizvod";

            OleDbConnection OleCn = new System.Data.OleDb.OleDbConnection(konekcija);
            OleDbCommand    OleCm = new System.Data.OleDb.OleDbCommand(komanda, OleCn);

            OleCm.Parameters.Add(new OleDbParameter("@Code", this.codeTextBox.Text.Trim()));
            OleDbDataReader dt;

            try
            {
                OleCn.Open();
                dt = OleCm.ExecuteReader();
                if (dt.Read())
                {
                    groupComboBox.SelectedIndex = groupComboBox.Items.IndexOf(dt["Ime_PG"].ToString());
                    description1TextBox.Text    = dt["Description"].ToString();
                    Sifra_Proizvod = Convert.ToInt32(dt["Sifra_Pro"].ToString());
                }
                dt.Close();
                OleCn.Close();
                this.codeTextBox.Enabled = false;
            }
            catch (Exception ex)
            {
                OleCn.Close();
                MessageBox.Show(ex.Message);
            }
        }
コード例 #33
0
ファイル: WinSetting.cs プロジェクト: g23988/FreeSpaceEyes
 //背景讀取access
 private void LoadAccess_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
         string find_text = (string)e.Argument;
         String strSQL    = "SELECT id,TargetName,TargetDeviceID FROM [WindowsTarget] WHERE TargetName LIKE '%" + find_text + "%'";
         System.Data.OleDb.OleDbConnection oleConn =
             new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=FreeSpaceEyesDB.mdb");
         oleConn.Open();
         System.Data.OleDb.OleDbCommand oleCmd =
             new System.Data.OleDb.OleDbCommand(strSQL, oleConn);
         OleDbDataReader thisReader = oleCmd.ExecuteReader();
         while (thisReader.Read())
         {
             string[] item = new string[3];
             item[0] = thisReader["id"].ToString();
             item[1] = thisReader["TargetName"].ToString();
             item[2] = thisReader["TargetDeviceID"].ToString();
             this.Invoke(new D_AddList(addlist), (object)item);
             Thread.Sleep(5);
         }
         thisReader.Close();
         oleConn.Close();
     }
     catch (Exception)
     {
     }
 }
コード例 #34
0
        private void bbatonishe_Click(object sender, EventArgs e)
        {
            dabse.OleDbCommand newCom = new dabse.OleDbCommand();
            var comand = new dabse.OleDbCommand("SELECT Код, Название FROM Дисциплины   WHERE Шифр_специальности=?", Date_baseone);

            comand.Parameters.Add("Шфр_спц", dabse.OleDbType.Integer, 255).Value = int.Parse(shifrSpecialnosti.Text);
            comand.Connection = Date_baseone;
            dabse.OleDbDataReader Result = comand.ExecuteReader();

            int    x = Result.FieldCount;
            String Name_disc, index_disk;

            while (Result.Read() == true)
            {
                index_disk = Result.GetValue(0).ToString();
                Name_disc  = Result.GetValue(1).ToString();
                dabse.OleDbCommand spisok = new dabse.OleDbCommand("insert into Дисциплины_обучение (Шифр_студента, Код_дисциплины) values (?, ?)", Date_baseone);
                spisok.Parameters.Add("Шифр_студента", dabse.OleDbType.Integer, 255).Value  = int.Parse(shifrStudenta.Text);
                spisok.Parameters.Add("Код_дисциплины", dabse.OleDbType.Integer, 255).Value = int.Parse(index_disk);
                spisok.Connection = Date_baseone;
                //MessageBox.Show(spisok.CommandText);
                spisok.ExecuteReader();
                //spisok.Close();
            }

            MessageBox.Show("Всё хорошо!!!");
        }
コード例 #35
0
ファイル: Frm_Main.cs プロジェクト: mahuidong/c-1200-II
 private void btn_Browser_Click(object sender, EventArgs e)
 {
     OpenFileDialog P_open = new OpenFileDialog();//创建打开文件对话框对象
     P_open.Filter = "文本文件|*.txt|所有文件|*.*";//设置筛选字符串
     if (P_open.ShowDialog() == DialogResult.OK)
     {
         txt_Path.Text = P_open.FileName;//显示文件路径
         string conn = string.Format(//创建连接字符串
              @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=text",
              P_open.FileName.Substring(0,P_open.FileName.LastIndexOf(@"\")));
         OleDbConnection P_OleDbConnection = new OleDbConnection(conn);//创建连接对象
         try
         {
             P_OleDbConnection.Open();//打开连接
             OleDbCommand cmd = new OleDbCommand(//创建命令对象
                 string.Format("select * from {0}",
                 P_open.FileName.Substring(P_open.FileName.LastIndexOf(@"\"),
                 P_open.FileName.Length - P_open.FileName.LastIndexOf(@"\"))),
                 P_OleDbConnection);
             OleDbDataReader oda = cmd.ExecuteReader();//得到数据读取器对象
             while (oda.Read())
             {
                txt_Message.Text  += oda[0].ToString();//得到文本文件中的字符串
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);//弹出消息对话框
         }
         finally
         {
             P_OleDbConnection.Close();//关闭连接
         }
     }
 }
コード例 #36
0
        public List <Object> getValues(string queryString)
        {
            List <Object> results = new List <Object>();

            configureConnection();
            using (conn)
            {
                System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(queryString, conn);
                try
                {
                    conn.Open();
                    System.Data.OleDb.OleDbDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        Object[] nextRow = new Object[reader.FieldCount];
                        reader.GetValues(nextRow);
                        results.Add(nextRow);
                    }
                    return(results);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    return(null);
                }
            }
        }
コード例 #37
0
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection();
        Conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("app_data/productsdb.mdb");
        Conn.Open();
        //Response.Write(Conn.State);

        System.Data.OleDb.OleDbCommand Comm = new System.Data.OleDb.OleDbCommand();
        System.Data.OleDb.OleDbDataReader dr;
        Comm.Connection = Conn;

        Comm.CommandText = "select productid, productname, productiondescription, price, qoh, imagelocation from products";

        if (Request.Params["categoryid"] != null && Request.Params["categoryid"].Length >0)
        {
            Comm.CommandText += " where categoryid = ?" ;
            Comm.Parameters.AddWithValue("anything", Request.Params["categoryid"].ToString());
        }

        dr = Comm.ExecuteReader();
        bool firstone = true;
        Response.Write("{\"product\":[");
        while (dr.Read())
        {
             if (!firstone)
            {
                Response.Write(",");
            }
            Response.Write(dr[0].ToString());

            firstone = false;

        }
        Response.Write("]}");
    }
コード例 #38
0
        public void NapolniFormaProizvod()
        {
            String komanda = "EXECUTE spPodatociProizvod";

            OleDbConnection OleCn = new System.Data.OleDb.OleDbConnection(konekcija);
            OleDbCommand    OleCm = new System.Data.OleDb.OleDbCommand(komanda, OleCn);

            OleCm.Parameters.Add(new OleDbParameter("@Code", this.vnesiTexBox.Text.Trim()));
            OleDbDataReader dt;

            try
            {
                OleCn.Open();
                dt = OleCm.ExecuteReader();
                if (dt.Read())
                {
                    groupLbl.Text       = dt["Ime_PG"].ToString();
                    descriptionLbl.Text = dt["Description"].ToString();
                    Sifra_Proizvod      = dt["Sifra_Pro"].ToString();
                }
                dt.Close();
                OleCn.Close();
            }
            catch (Exception ex)
            {
                OleCn.Close();
                MessageBox.Show(ex.Message);
            }
        }
コード例 #39
0
ファイル: LinuxSetting.cs プロジェクト: g23988/FreeSpaceEyes
        private void TargetListView_ItemMouseClick(object sender, Telerik.WinControls.UI.ListViewItemEventArgs e)
        {
            ListViewDataItem item = TargetListView.SelectedItem;
            //將資料拉出來到ui上
            // === 對 Access 資料庫下SQL語法 ===
            //// Transact-SQL 陳述式
            String strSQL = "SELECT id,TargetName,TargetIP,TargetAlert,TargetRes,TargetSpaceLog,TargetWarning FROM [LinuxTarget] WHERE id =" + int.Parse(item[0].ToString());

            System.Data.OleDb.OleDbConnection oleConn =
                new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=FreeSpaceEyesDB.mdb");
            //// 開啟資料庫連接。
            oleConn.Open();
            //// OleDbCommand (String, OleDbConnection) : 使用查詢的文字和 OleDbConnection,初始化 OleDbCommand 類別的新執行個體。
            System.Data.OleDb.OleDbCommand oleCmd =
                new System.Data.OleDb.OleDbCommand(strSQL, oleConn);
            OleDbDataReader thisReader = oleCmd.ExecuteReader();//建立OleDbDataReader用來存放從Access裡面讀取出來的

            //拉到ui
            while (thisReader.Read())
            {
                ShowTargetID.Text      = thisReader["id"].ToString();
                ShowTargetName.Text    = thisReader["TargetName"].ToString();
                ShowTargetIP.Text      = thisReader["TargetIP"].ToString();
                ShowTargetAlert.Text   = thisReader["TargetAlert"].ToString();
                ShowTargetRes.Text     = thisReader["TargetRes"].ToString();
                ShowTargetWarning.Text = thisReader["TargetWarning"].ToString();
            }
            //// 關閉資料庫連接。
            thisReader.Close();
            oleConn.Close();
            //啟動更新即刪除
            updata_btn.Enabled  = true;
            deldata_btn.Enabled = true;
        }
コード例 #40
0
ファイル: Reader.cs プロジェクト: JRDuenow/ProgressBuilder
        /// <summary>
        /// Reads the selected file and places the contents into a DataTable.
        /// </summary>
        /// <returns>Datatable of students in file</returns>
        public DataTable ReadFile()
        {
            DataTable data = new DataTable();

            try
            {
                using (cmd = con.CreateCommand())
                {
                    cmd.CommandText = string.Format("SELECT * from [{0}]", file.Name);
                    con.Open();

                    using (dr = cmd.ExecuteReader())
                    {
                        data.Load(dr);
                    }
                }
            }
            catch (OleDbException oExe)
            {
                Debug.WriteLine(oExe.Message);
            }
            finally
            {
                con.Close();
            }

            return data;
        }
コード例 #41
0
 private bool CheckApologizeExisted()
 {
     OleDbConnection Con = ET_Lib.E_trainingConnection;
     OleDbCommand Cmd = new OleDbCommand("SELECT TRshehId, ApologyDate, ApologyReson FROM DowraApology WHERE (TRshehId = " + ViewState["TRshehId"].ToString() + ")", Con);
     OleDbDataReader Dr;
     try
     {
         Con.Open();
         Dr = Cmd.ExecuteReader();
         if (Dr.HasRows)
         {
             Dr.Read();
             TxtReason.Text = Dr.GetValue(2).ToString();
             LblApologizeDate.Text = Convert.ToDateTime(Dr.GetValue(1).ToString()).ToShortDateString().ToString();
             Cmd.CommandText = "SELECT DowraName FROM Dowraat WHERE (DowraId = " + Request.QueryString["Courseid"].ToString() + ")";
             Dr.Close();
             LblCourseName.Text = Cmd.ExecuteScalar().ToString();
             Con.Close();
             return true;
         }
         else
         {
             Con.Close();
             return false;
         }
     }
     catch (Exception ex)
     {
         LblState.Text = ex.Message;
         LblState.Visible = true;
         Con.Close();
         return false;
     }
 }
コード例 #42
0
ファイル: Program.cs プロジェクト: krstan4o/TelerikAcademy
        //Create an Excel file with 2 columns: name and score:
        //Write a program that reads your MS Excel file through
        //the OLE DB data provider and displays the name and score row by row.

        static void Main()
        {
            OleDbConnection dbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" +
            @"Data Source=D:\Telerik\DataBases\HW\ADONET\06. ReadExcel\Table.xlsx;Extended Properties=""Excel 12.0 XML;HDR=Yes""");
            OleDbCommand myCommand = new OleDbCommand("select * from [Sheet1$]", dbConn);
            dbConn.Open();
            //First way
            //using (dbConn) - I think it is better to use dbConn in using clause, but for the demo issues i dont use using.
            //{
            OleDbDataReader reader = myCommand.ExecuteReader();

            while (reader.Read())
            {
                string name = (string)reader["Name"];
                double score = (double)reader["Score"];
                Console.WriteLine("{0} - score: {1}", name, score);
            }
            //}

            dbConn.Close();
            //Second way
            dbConn.Open();
            Console.WriteLine();
            Console.WriteLine("Second Way");
            Console.WriteLine("----------");
            DataTable dataSet = new DataTable();
            OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [Sheet1$]", dbConn);
            adapter.Fill(dataSet);

            foreach (DataRow item in dataSet.Rows)
            {
                Console.WriteLine("{0}|{1}", item.ItemArray[0], item.ItemArray[1]);
            }
            dbConn.Close();
        }
コード例 #43
0
	public void GetEmailContent(int CategoryID)
	{
		OleDbConnection oleDBConnetion = new OleDbConnection();
		oleDBConnetion.ConnectionString = 
			"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("../App_Data/emailclient.mdb") + "; User Id=; Password="******"SELECT EmailID, EmailCategoryID, EmailSubject, EmailFrom, EmailContent FROM EmailClient where EmailCategoryID = " + CategoryID + "";

		OleDbDataReader dataReader;
		oleDBConnetion.Open();				
		dataReader = oleDBCommand.ExecuteReader();
		emailList.DataSource = dataReader;
		emailList.DataBind();
		dataReader.Close();
		
		// get the first email from the list for loading it's details
		OleDbCommand topOleDBCommand = new OleDbCommand();
		topOleDBCommand.CommandType = CommandType.Text;
		topOleDBCommand.Connection = oleDBConnetion;
		topOleDBCommand.CommandText = "SELECT top 1 EmailID FROM EmailClient where EmailCategoryID = " + CategoryID + "";
		OleDbDataReader topDataReader;
		topDataReader = topOleDBCommand.ExecuteReader();
		if (topDataReader.Read()) selectedEmailID = topDataReader.GetInt32(0);
		topDataReader.Close();
		
		oleDBConnetion.Close();
	}
コード例 #44
0
        public void NapolniForma()
        {
            String komanda = "EXECUTE spPodatociFirma";

            OleDbConnection OleCn = new System.Data.OleDb.OleDbConnection(konekcija);
            OleDbCommand    OleCm = new System.Data.OleDb.OleDbCommand(komanda, OleCn);
            OleDbDataReader dt;

            OleCm.Parameters.Add(new OleDbParameter("@Firma", this.companyNameTextBox.Text.Trim()));

            try
            {
                OleCn.Open();
                dt = OleCm.ExecuteReader();
                if (dt.Read())
                {
                    contactTxtBox.Text            = dt["Contact"].ToString();
                    telTextBox.Text               = dt["Tel"].ToString();
                    faxTexBox.Text                = dt["Fax"].ToString();
                    emailTextBox.Text             = dt["Email"].ToString();
                    zipcodeTextBox.Text           = dt["ZipCode"].ToString();
                    cityTextBox.Text              = dt["City"].ToString();
                    stateComboBox.SelectedIndex   = stateComboBox.Items.IndexOf(dt["State"].ToString());
                    countryComboBox.SelectedIndex = countryComboBox.Items.IndexOf(dt["Country"].ToString());
                    Sifra_Firma = Convert.ToInt32(dt["Sifra_Firma"].ToString());
                }
            }
            catch (Exception ex)
            {
                OleCn.Close();
                MessageBox.Show(ex.Message);
            }
            novoImePrikaziControli();
            companyNameTextBox.Enabled = false;
        }
コード例 #45
0
ファイル: frmProduct.cs プロジェクト: balavigneshs/iMgmt
        public void FillCombo()
        {
            try
            {

                con = new OleDbConnection(cs);
                con.Open();
                string ct = "select RTRIM(CategoryName) from Category order by CategoryName";
                cmd = new OleDbCommand(ct);
                cmd.Connection = con;
                rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    cmbCategory.Items.Add(rdr[0]);
                }
                con.Close();
                con = new OleDbConnection(cs);
                con.Open();
                string ct1 = "select RTRIM(CompanyName) from Company order by CompanyName";
                cmd = new OleDbCommand(ct1);
                cmd.Connection = con;
                rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    cmbCompany.Items.Add(rdr[0]);
                }
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #46
0
ファイル: DerbyRolesHelper.cs プロジェクト: runefs/Marvin
		public static int Roles_CreateRole (DbConnection connection, string applicationName, string rolename)
		{
			string appId = (string) DerbyApplicationsHelper.Applications_CreateApplication (connection, applicationName);
			if (appId == null)
				return 1;

			string querySelect = "SELECT RoleName FROM aspnet_Roles WHERE ApplicationId = ? AND LoweredRoleName = ?";
			OleDbCommand cmdSelect = new OleDbCommand (querySelect, (OleDbConnection) connection);
			AddParameter (cmdSelect, "ApplicationId", appId);
			AddParameter (cmdSelect, "LoweredRoleName", rolename.ToLowerInvariant ());

			using (OleDbDataReader reader = cmdSelect.ExecuteReader ()) {
				if (reader.Read ())
					return 2; // role already exists
			}

			string queryInsert = "INSERT INTO aspnet_Roles (ApplicationId, RoleId, RoleName, LoweredRoleName) VALUES (?, ?, ?, ?)";
			OleDbCommand cmdInsert = new OleDbCommand (queryInsert, (OleDbConnection) connection);
			AddParameter (cmdInsert, "ApplicationId", appId);
			AddParameter (cmdInsert, "RoleId", Guid.NewGuid ().ToString ());
			AddParameter (cmdInsert, "RoleName", rolename);
			AddParameter (cmdInsert, "LoweredRoleName", rolename.ToLowerInvariant ());
			cmdInsert.ExecuteNonQuery ();

			return 0;
		}
コード例 #47
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        int lgflg = 0;

        OleDbConnection conn = new OleDbConnection(ConfigurationSettings.AppSettings["classDB"]);
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM student WHERE studentpassword = '******' AND email = '" + userName.Text + "'", conn);

        conn.Open();
        OleDbDataReader myReader = cmd.ExecuteReader();

        while (myReader.Read())
        {
            lgflg = 1;
            Session.Add("fname", myReader["Contact_name"]);
            Session.Add("address", myReader["address"]);
            Session.Add("city", myReader["city"]);
            Session.Add("state", myReader["state"]);
            Session.Add("zipcode", myReader["zipcode"]);
        }
        myReader.Close();
        conn.Close();

        if (lgflg == 1)
        {
            Response.Write(Session["fname"]);
        }
        else
        {
            error.Visible = true;
        }
    }
コード例 #48
0
        //---------------------------------------------------------------------
        public static void ConstantQuery(OleDbConnection dbcon, CodeGenerator cg)
        {
            cg.ConstantList.Clear();
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM Constants ORDER BY Topic, ID", dbcon);
            OleDbDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                Constant curConst = new Constant();
                curConst.Name = dr["Name"].ToString();
                curConst.Value = dr["Value"].ToString();
                Int32 nTopic = Convert.ToInt32(dr["Topic"].ToString());
                if (nTopic > 0)
                {
                    curConst.Topic = cg.TopicList[nTopic - 1].Name.ToString();
                }
                else
                {
                    curConst.Topic = "";
                }
                curConst.Description = dr["Description"].ToString();
                cg.ConstantList.Add(curConst);

                //curConst.Print();
            }

            dr.Close();
        }
コード例 #49
0
ファイル: urunler.cs プロジェクト: dgncn/fotosale
        public DataTable sepetcevir(string uyeID, string map)
        {

            OleDbConnection cnn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" + map);
            cnn.Open();
            OleDbCommand cmd = new OleDbCommand("select sepet from uyeler where uyeid=" + uyeID, cnn);
            OleDbDataReader rdr = cmd.ExecuteReader();
            rdr.Read();
            string[] urunler = rdr[0].ToString().Split(',');

            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("fid"), new DataColumn("aciklama"), new DataColumn("fiyat") });

            if (rdr[0].ToString() != "")
            {
                foreach (string item in urunler)
                {
                    cmd.Dispose();
                    string fid = item;

                    cmd = new OleDbCommand("select * from fotolar where fot_id=" + fid, cnn);
                    OleDbDataReader rdr2 = cmd.ExecuteReader();
                    rdr2.Read();
                    string ack = rdr2[5].ToString();
                    string fiyat = rdr2[6].ToString();

                    dt.Rows.Add(fid, ack, fiyat);
                }
            }

            cnn.Close();

            return dt;
        }
コード例 #50
0
        //---------------------------------------------------------------------
        public static void DatatypeQuery(OleDbConnection dbcon, CodeGenerator cg)
        {
            cg.DataTypeList.Clear();
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM DataTypes", dbcon);
            OleDbDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                DataType curDatatype = new DataType();

                curDatatype.ID = Convert.ToInt32(dr["ID"].ToString());
                curDatatype.DataTypeName = dr["DataTypeName"].ToString();
                curDatatype.CType = dr["CType"].ToString();
                curDatatype.CTypeDef = dr["CTypeDef"].ToString();

                curDatatype.CSType = dr["CSType"].ToString();
                curDatatype.CSTypeDef = dr["CSTypeDef"].ToString();

                curDatatype.VBType = dr["VBType"].ToString();
                curDatatype.VBTypeDef = dr["VBTypeDef"].ToString();

                curDatatype.PythonType = dr["PythonType"].ToString();
                curDatatype.PythonTypeDef = dr["PythonTypeDef"].ToString();

                cg.DataTypeList.Add(curDatatype);
            }

            dr.Close();
        }
コード例 #51
0
        protected void datefilterPlanMeal_DayRender(object sender, DayRenderEventArgs e)
        {
            OleDbCommand command = new OleDbCommand("SELECT * FROM PlannedMeal WHERE UserDataID = " + userID + " ORDER BY CreatedDate DESC", myConnection);

            OleDbDataReader dr = command.ExecuteReader();
            // Read DataReader till it reaches the end
            while (dr.Read() == true)
            {
                // Assign the Calendar control dates
                // already contained in the database
                //datefilterPlanMeal.SelectedDates.Add((DateTime)dr["CreatedDate"]);
                if (e.Day.Date == (DateTime)dr["CreatedDate"])
                {
                    e.Cell.BackColor = System.Drawing.Color.Silver;
                }
            }
            if (e.Day.IsSelected)
            {
                e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#4db6ac");
                e.Cell.ForeColor = System.Drawing.Color.White;
            }

            // Close DataReader
            dr.Close();
        }
 public Window_jianzhan4()
 {
     InitializeComponent();
     systime.Content = DateTime.Now.ToShortTimeString();
     OleDbDataReader dr;
     OleDbConnection conn = new OleDbConnection(odbcConnStr);
     string sql = "select * from rearview_checking";
     OleDbCommand cmd = new OleDbCommand(sql, conn);
     conn.Open();
     dr = cmd.ExecuteReader();
     if (dr.Read())
     {
         string s;
         double t,k;
         station_point.Content = dr.GetString(1).ToString();
         rearview_point.Content = dr.GetString(2).ToString();
         BS.Content = dr.GetString(3).ToString();
         s = BS.Content.ToString();
         t = Convert.ToDouble(s);
         Random ran = new Random();
         k = ran.Next(0, 200)*0.0001;
         t = k + t;
         HA.Content = t.ToString();
         dHA.Content = k.ToString();
     }
     conn.Close();                    
 }
コード例 #53
0
ファイル: FMAD104.cs プロジェクト: balasmani/texpro
 private void fill_form(string p_id)
 {
     String strQuery = String.Empty;
     OleDbConnection sqlConn = new OleDbConnection();
     OleDbCommand sqlComm = new OleDbCommand();
     OleDbDataReader sqlRead;// = new OleDbDataReader();
     DateTime strReturn = DateTime.Now;
     //
     sqlConn.ConnectionString = PCPUB.m_oledb_connection.ToString();
     sqlConn.Open();
     //
     strQuery = String.Empty;
     strQuery += " SELECT";
     strQuery += " [yarn_count_id],";
     strQuery += " [yarn_count_name]";
     strQuery += " FROM [tis_yarn_count]";
     strQuery += " WHERE [yarn_count_id] = '" + p_id + "'";
     //
     sqlComm.Connection = sqlConn;
     sqlComm.CommandText = strQuery.ToString();
     sqlRead = sqlComm.ExecuteReader();
     //
     if (sqlRead.Read())
     {
         txt_yarn_count_id.Text = sqlRead["yarn_count_id"].ToString();
         txt_yarn_count_name.Text = sqlRead["yarn_count_name"].ToString();
     }
     //
     sqlRead.Close();
     sqlConn.Close();
     sqlRead.Dispose();
     sqlComm.Dispose();
     sqlConn.Dispose();
 }
コード例 #54
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!this.IsPostBack)
     {
         string name = Request["name"].ToString();
         OleDbConnection con = DB.createDB();
         con.Open();
         OleDbCommand cmd = new OleDbCommand();//声明一个OleDbCommand的 cmd对象,并将其实例化
         cmd.Connection = con;
         cmd.CommandText = "select * from tb_qianfei where name='" + name + "'";
         cmd.ExecuteNonQuery();
         OleDbDataReader sdr = cmd.ExecuteReader();
         sdr.Read();
         if (name!= "")
         {
             this.lblqfname.Text = sdr.GetString(0).ToString();
             this.lblzz.Text = sdr.GetString(1);
             this.lbllb.Text = sdr.GetString(2);
             this.lblrqzs.Text = sdr.GetDateTime(3).ToShortDateString();
             this.lblzzsj.Text = sdr.GetDateTime(4).ToShortDateString();
             this.lblje.Text = sdr.GetString(5).ToString();
             this.Lblzt.Text = sdr.GetString(6).ToString();
             this.lbljsr.Text = sdr.GetString(7).ToString();
         }
         else
         {
             Response.Write("暂无主题,不能显示");
             Response.Redirect("Default.aspx");//将该页跳转到指定的页面中
         }
     }
 }
コード例 #55
0
        private void button3_Click(object sender, EventArgs e)
        {
            String surname;
            String groupName;
            String specialityName;
            String formOfEducation;
            String yearsofEducation;

            List <String> surnameMas          = new List <String>();
            List <String> groupNameMas        = new List <String>();
            List <String> specialityNameMas   = new List <String>();
            List <String> formOfEducationMas  = new List <String>();
            List <String> yearsofEducationMas = new List <String>();

            var Command = new dabse.OleDbCommand("SELECT Студенты.Фамилия, Группы.Название, Специальности.Название, Студенты.Форма_обучения, Специальности.Срок_обучения FROM  Группы, Группы_обучение, Студенты, Специальности WHERE Группы.Номер = Группы_обучение.Номер_группы AND Группы_обучение.Шифр_студента = Студенты.Шифр AND Студенты.Специальность = Специальности.Шифр AND Студенты.Шифр = " + thirdshifrsudenta.Text + "AND Группы_обучение.Год = " + thirdnameofsubject.Text, Date_baseone);

            dabse.OleDbDataReader Ask3 = Command.ExecuteReader();

            while (Ask3.Read() == true)
            {
                surname          = Ask3[0].ToString();
                groupName        = Ask3[1].ToString();
                specialityName   = Ask3[2].ToString();
                formOfEducation  = Ask3[3].ToString();
                yearsofEducation = Ask3[4].ToString();

                surnameMas.Add(surname);
                groupNameMas.Add(groupName);
                specialityNameMas.Add(specialityName);
                formOfEducationMas.Add(formOfEducation);
                yearsofEducationMas.Add(yearsofEducation);
            }

            wooord.Application wordApp = new wooord.Application();
            wordApp.Visible = true;
            object oMissing = Type.Missing;

            wooord.Document  wordDoc;
            wooord.Paragraph wordPar;
            wooord.Range     wordRan;
            wordDoc = wordApp.Documents.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            //задаём форматирование для первого абзаца, которое будет так же и для всего документа, но
            //это не страшно. Последующие абзацы будут иметь другое форматирование

            Object begin = Type.Missing;
            Object end   = Type.Missing;

            wordRan = wordDoc.Range(ref begin, ref end);
            wordRan.ParagraphFormat.Alignment = wooord.WdParagraphAlignment.wdAlignParagraphCenter;
            wordRan.Text = "Справка";

            //теперь задаём форматирование следующего абзаца

            wordPar = wordDoc.Paragraphs.Add(ref oMissing);
            wordDoc.Paragraphs[2].Range.ParagraphFormat.Alignment = wooord.WdParagraphAlignment.wdAlignParagraphLeft;
            wordDoc.Paragraphs[2].Range.Font.Size = 10;
            wordDoc.Paragraphs[2].Range.Text      = "Студент " + surnameMas[0] + " обучается в группе " + groupNameMas[0] + " по специальности " + specialityNameMas[0] + ". Форма обучения – " + formOfEducationMas[0] + ". Срок обучения – " + yearsofEducationMas[0] + ".";
        }
コード例 #56
0
        public void Search()
        {
            //create a connection object and command object, to connect the Index Server
            System.Data.OleDb.OleDbConnection odbSearch = new System.Data.OleDb.OleDbConnection("Provider=\"MSIDXS\";Data Source=\"docSearch\";");
            System.Data.OleDb.OleDbCommand    cmdSearch = new System.Data.OleDb.OleDbCommand();
            //assign connection to command object cmdSearch
            cmdSearch.Connection = odbSearch;

            //Query to search a free text string in the catalog in the contents of the indexed documents in the catalog
            string searchText = txtSearch.Text.Replace("'", "''");

            cmdSearch.CommandText = "select doctitle, filename, vpath, rank, characterization from scope() where FREETEXT(Contents, '" + searchText + "') order by rank desc ";

            odbSearch.Open();

            try
            {
                //execute search query
                OleDbDataReader rdrSearch = cmdSearch.ExecuteReader();
                //loop through each result and bind it to the repeater control
                while (rdrSearch.Read())
                {
                    //Assemble the search result text and abstract
                    getpagelink(rdrSearch[0].ToString(), rdrSearch[2].ToString(), rdrSearch[4].ToString());
                }
            }
            catch (Exception ex)
            {
                lbl.Text = "Search Error: " + ex.Message + "<br>";
            }

            odbSearch.Close();

            // Populate the repeater control with the Items DataSet
            PagedDataSource objPds = new PagedDataSource();

            objPds.DataSource = values;

            // Indicate that the data should be paged
            objPds.AllowPaging = true;

            // Set the number of items you wish to display per page
            objPds.PageSize = 10;

            // Set the PagedDataSource's current page
            objPds.CurrentPageIndex = CurrentPage;

            //Display a summary for the current search
            resultSummary.Text = "Your search for <b>" + txtSearch.Text + "</b> Returned " + (cnt - 1) + " Results.  " +
                                 "<br>Page: " + (CurrentPage + 1).ToString() + " of " + objPds.PageCount.ToString();

            // Disable Prev or Next buttons if necessary
            cmdPrev.Enabled = !objPds.IsFirstPage;
            cmdNext.Enabled = !objPds.IsLastPage;

            searchResults.DataSource = objPds;
            searchResults.DataBind();
        }
コード例 #57
0
        private void btnBrowser_Click(object sender, EventArgs e)
        {
            g_ListXeLaiXe.Clear();
            this.openFileDialog1.FileName = "*.xls";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string filename = StringTools.TrimSpace(openFileDialog1.FileName);

                txtPath.Text = filename;
                if (filename.Length > 0)
                {
                    string m_sConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + filename + "; Extended Properties=\"Excel 8.0;HDR=YES\"";

                    OleDbConnection conn = new OleDbConnection(m_sConn);
                    conn.Open();

                    // SoHieuXe
                    // TenLaiXe
                    // SoThe
                    // GioRa

                    OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("SELECT SoHieuXe,TenLaiXe,SoThe,GioRa FROM [DSLaiXe$] ", conn);

                    OleDbDataReader rdr; //= new OleDbDataReader();
                    rdr = cmd.ExecuteReader();



                    while (rdr.Read())
                    {
                        try
                        {
                            int        iSoHieuXe  = Convert.ToInt32(rdr["SoHieuXe"].ToString());
                            string     GioRa      = rdr["GioRa"].ToString();
                            string     SoThe      = Convert.ToString(rdr["SoThe"].ToString());
                            clsXeLaiXe objXeLaiXe = new clsXeLaiXe(this.GetSoHieuXe(iSoHieuXe), rdr["TenLaiXe"].ToString(), this.GetGioRa(GioRa, g_GioHienTaiServer), SoThe);
                            g_ListXeLaiXe.Add(objXeLaiXe);
                        }
                        catch (Exception ex)
                        {
                            // loại bỏ các dòng lỗi
                        }
                    }

                    dataGridView1.DataSource = g_ListXeLaiXe;


                    rdr.Close();
                    conn.Close();

                    if ((g_ListXeLaiXe != null) && (g_ListXeLaiXe.Count > 0))
                    {
                        btnImport.Enabled = true;
                    }
                }
            }
        }
コード例 #58
0
        private void button1_Click(object sender, EventArgs e)
        {
            String        name;
            String        mark;
            List <String> one = new List <String>();
            List <String> two = new List <String>();

            command = new dabse.OleDbCommand("Select Дисциплины.Название, Дисциплины_обучение.Балл From Дисциплины, Дисциплины_обучение, Студенты Where Дисциплины.Код = Дисциплины_обучение.Код_дисциплины and Студенты.Шифр = Дисциплины_обучение.Шифр_студента and Студенты.Шифр = " + firststudensshifr.Text + " order by Дисциплины_обучение.Балл, Дисциплины.Название", Date_baseone);
            dabse.OleDbDataReader result = command.ExecuteReader();
            wooord.Application    app    = new wooord.Application();
            Object missing = Type.Missing;

            app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            wooord.Document docec = app.ActiveDocument;
            wooord.Range    range = docec.Paragraphs[docec.Paragraphs.Count].Range;

            while (result.Read())
            {
                name = result[1].ToString();
                mark = result[0].ToString();

                one.Add(name);
                two.Add(mark);
            }

            int len = two.Count;

            docec.Tables.Add(range, len + 1, 2, ref missing, ref missing);
            docec.Tables[1].Cell(1, 1).Range.Text = "Название дисциплины";
            docec.Tables[1].Cell(1, 2).Range.Text = "Балл";

            for (int i = 0; i < len; i++)
            {
                docec.Tables[1].Cell(i + 2, 1).Range.Text = two[i];
                docec.Tables[1].Cell(i + 2, 2).Range.Text = one[i];
            }

            wooord.Border[] bords = new wooord.Border[6];

            wooord.Table table = docec.Tables[docec.Tables.Count];

            bords[0] = table.Borders[wooord.WdBorderType.wdBorderLeft];
            bords[1] = table.Borders[wooord.WdBorderType.wdBorderRight];
            bords[2] = table.Borders[wooord.WdBorderType.wdBorderTop];
            bords[3] = table.Borders[wooord.WdBorderType.wdBorderBottom];
            bords[4] = table.Borders[wooord.WdBorderType.wdBorderVertical];
            bords[5] = table.Borders[wooord.WdBorderType.wdBorderHorizontal];

            foreach (wooord.Border border in bords)
            {
                border.LineStyle = wooord.WdLineStyle.wdLineStyleSingle;
                border.Color     = wooord.WdColor.wdColorBlack;
            }
            app.Visible = true;
        }
コード例 #59
0
ファイル: SnowLib.cs プロジェクト: bakasnow/TiebaDuster
    public static System.Data.DataTable getTable(string 参数_数据库路径, string 参数_SQL语句)
    {
        //初始化
        System.Data.DataTable dt = new System.Data.DataTable();

        try
        {
            //1、建立连接 C#操作Access之读取mdb
            string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + 参数_数据库路径 + ";";
            System.Data.OleDb.OleDbConnection odcConnection = new System.Data.OleDb.OleDbConnection(strConn);

            //2、打开连接 C#操作Access之读取mdb
            odcConnection.Open();

            //建立SQL查询
            System.Data.OleDb.OleDbCommand odCommand = odcConnection.CreateCommand();

            //3、输入查询语句 C#操作Access之读取mdb
            odCommand.CommandText = 参数_SQL语句;

            //建立读取
            System.Data.OleDb.OleDbDataReader odrReader = odCommand.ExecuteReader();

            //查询并显示数据
            int size = odrReader.FieldCount;

            for (int i = 0; i < size; i++)
            {
                //Console.WriteLine("{0} {1}", "列", odrReader.GetName(i).ToString());
                dt.Columns.Add(odrReader.GetName(i).ToString(), typeof(string));
            }

            while (odrReader.Read())
            {
                System.Data.DataRow dr = dt.NewRow();
                for (int i = 0; i < size; i++)
                {
                    //Console.WriteLine("{0} {1}", odrReader.GetName(i).ToString(), odrReader[odrReader.GetName(i)].ToString());
                    dr[odrReader.GetName(i).ToString()] = odrReader[odrReader.GetName(i)].ToString();
                }
                dt.Rows.Add(dr);
            }

            //关闭连接 C#操作Access之读取mdb
            odrReader.Close();
            odcConnection.Close();

            return(dt);
        }
        catch
        {
            return(dt);
        }
    }
コード例 #60
0
        private void Form2_Load(object sender, System.EventArgs e)
        {
            con_1.Open();
            Delete1.ExecuteNonQuery();
            for (int j = 0; j < _3.i; j++)
            {
                oleDbInsertCommand1.Parameters["ime_sektorja"].Value = "Sektor_" + _3.niz_sektorjev[j].ToString();
                if (_3.vsi_sektorji_zasedeni)
                {
                    oleDbInsertCommand1.Parameters["st_gledalcev"].Value = _3.st_vseh_mest_za_sektor;
                }
                else
                {
                    oleDbInsertCommand1.Parameters["st_gledalcev"].Value = 0;
                }
                oleDbInsertCommand1.ExecuteNonQuery();
            }
            con_1.Close();
            oleDbDataAdapter1.Fill(dataSet11, "sektorji");
            pb_1          = this.BindingContext[dataSet11, "sektorji"];
            pb_1.Position = 0;

            if (_3.vsi_sektorji_zasedeni)
            {
                stevilo_nedolocenih_gledalcev.Text = "0";
            }
            else
            {
                System.Data.OleDb.OleDbDataReader dr;
                con_1.Open();
                dr = oleDbSelectCommand1.ExecuteReader();
                while (dr.Read())
                {
                    _3.vs_gled_1 += Convert.ToInt32(dr["st_gledalcev"]);
                }
                dr.Close();
                con_1.Close();
                stevilo_nedolocenih_gledalcev.Text = Convert.ToString(_3.st_z_mest - _3.vs_gled_1);
            }
            st_zas_sektorjev_2.Text = "0";
        }