Beispiel #1
1
        private void buttonInfoMessage_Click(object sender, EventArgs e)
        {

            /**** Create this Store Procedure in the tempdb database first ****
                        Create Proc TestInfoMessage
                        as
                        Print 'Using a Print Statement'
                        RaisError('RaisError in Stored Procedures', 9, 1)
            ****************************************************/

            //1. Make a Connection
            System.Data.OleDb.OleDbConnection objOleCon = new System.Data.OleDb.OleDbConnection();
            objOleCon.ConnectionString = strConnection;
            objOleCon.Open();

            objOleCon.InfoMessage += new System.Data.OleDb.OleDbInfoMessageEventHandler(objOleCon_InfoMessage);

            //2. Issue a Command
            System.Data.OleDb.OleDbCommand objCmd;
            objCmd = new System.Data.OleDb.OleDbCommand("Raiserror('Typical Message Goes Here', 9, 1)", objOleCon);
            objCmd.ExecuteNonQuery();
            objCmd = new System.Data.OleDb.OleDbCommand("Exec TestInfoMessage", objOleCon); //This executes the stored procedure.
            objCmd.ExecuteNonQuery();

            //3. Process the Results
            /** No Results at this time **/

            //4. Clean up code
            objOleCon.Close();
        }
        protected void btnGo_Click(object sender, EventArgs e)
        {
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
            string sql = "";
            System.Data.DataSet ds = new System.Data.DataSet();
            System.Data.OleDb.OleDbDataReader dr;
            System.Data.OleDb.OleDbCommand comm = new System.Data.OleDb.OleDbCommand();
            //http://www.c-sharpcorner.com/UploadFile/dchoksi/transaction02132007020042AM/transaction.aspx
            //get this from connectionstrings.com/access
            conn.ConnectionString = txtConnString.Text;
            conn.Open();
            //here I can talk to my db...
            System.Data.OleDb.OleDbTransaction Trans;
            Trans = conn.BeginTransaction(System.Data.IsolationLevel.Chaos);

            try
            {

                comm.Connection = conn;
                comm.Transaction = Trans;
               // Trans.Begin();

                //Console.WriteLine(conn.State);
                sql = txtSQL.Text;
                comm.CommandText = sql;
                if (sql.ToLower().IndexOf("select") == 0)
                {
                    dr = comm.ExecuteReader();
                    while (dr.Read())
                    {
                        txtresults.Text = dr.GetValue(0).ToString();
                    }
                }
                else
                {
                    txtresults.Text = comm.ExecuteNonQuery().ToString();
                }
                Trans.Commit();
            }
            catch (Exception ex)
            {
                txtresults.Text = ex.Message;
                Trans.Rollback();
            }
            finally
            {

                comm.Dispose();
                conn.Close();
                conn = null;
            }
        }
 public DataTable SelectToDataTable(string sql)
 {
     //set connection
     System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection();
     con.ConnectionString = connectString;
     //set commandtext
     System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
     command.CommandText = sql;
     command.Connection = con;
     //set adapter
     System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
     adapter.SelectCommand = command;
     //creat a datatable
     DataTable dt = new DataTable();
     try
     {
         //open this connection
         con.Open();
         adapter.Fill(dt);
     }
     catch (Exception ex)
     {
         //throw new Exception
         con.Close();
     }
     finally
     {
         //close this connection
         con.Close();
     }
     //return a datatable
     return dt;
 }
Beispiel #4
0
 /// <summary>
 /// M�todo necesario para admitir el Dise�ador, no se puede modificar
 /// el contenido del m�todo con el editor de c�digo.
 /// </summary>
 private void InitializeComponent()
 {
     this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
     this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
     this.oleDbDataAdapter1 = new System.Data.OleDb.OleDbDataAdapter();
     this.dsFicha1 = new ficha_antecedentes_personales.dsFicha();
     ((System.ComponentModel.ISupportInitialize)(this.dsFicha1)).BeginInit();
     //
     // oleDbConnection1
     //
     this.oleDbConnection1.ConnectionString = "Provider=SQLOLEDB;server=edoras;OLE DB Services = -2;uid=protic;pwd=,.protic;init" +
         "ial catalog=protic2";
     //
     // oleDbSelectCommand1
     //
     this.oleDbSelectCommand1.CommandText = @"select '' as nombre, '' as rut, '' as pasaporte, '' as fecha_nac, '' as fono, '' as nacionalidad, '' as Estado_civil, '' as Direccion, '' as comuna, '' as ciudad, '' as region, '' as colegio_egreso, '' as ano_egreso, '' as proced_educ, '' as inst_educ_sup, '' as Carrera, '' as ano_ingr, '' as FinanciaEst, '' as ultimo_post_ncorr, '' as nombre_sost_ec, '' as RUT_sost_ec, '' as fnac_sost_ec, '' as edad_sost, '' as fono_sost_ec, '' as pare_sost_ec, '' as dire_tdesc_sost_ec, '' as comu_sost_ec, '' as ciud_sost_ec, '' as regi_sost_ec";
     this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
     //
     // oleDbDataAdapter1
     //
     this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1;
     //
     // dsFicha1
     //
     this.dsFicha1.DataSetName = "dsFicha";
     this.dsFicha1.Locale = new System.Globalization.CultureInfo("es-CL");
     this.dsFicha1.Namespace = "http://www.tempuri.org/dsFicha.xsd";
     this.Load += new System.EventHandler(this.Page_Load);
     ((System.ComponentModel.ISupportInitialize)(this.dsFicha1)).EndInit();
 }
 public System.Collections.Generic.List<string> GetColumnNames(string file, string table)
 {
     System.Data.DataTable dataSet = new System.Data.DataTable();
     string connString = "";
     if (Global.filepassword != "")
     {
         if (Path.GetExtension(file).ToString().ToUpper() != ".ACCDB")
             connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Jet OLEDB:Database Password="******"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file + ";Jet OLEDB:Database Password="******".ACCDB")
             connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file;
         else
             connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file + ";Persist Security Info=False;";
     }
     using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(connString))
     {
         connection.Open();
         System.Data.OleDb.OleDbCommand Command = new System.Data.OleDb.OleDbCommand("SELECT * FROM " + table, connection);
         using (System.Data.OleDb.OleDbDataAdapter dataAdapter = new System.Data.OleDb.OleDbDataAdapter(Command))
         {
             dataAdapter.Fill(dataSet);
         }
     }
     System.Collections.Generic.List<string> columns = new System.Collections.Generic.List<string>();
     for (int i = 0; i < dataSet.Columns.Count; i++)
     {
         columns.Add(dataSet.Columns[i].ColumnName);
     }
     return columns;
 }
        protected void btnInsert_Click(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/products.mdb");
            Conn.Open();
            //Response.Write(Conn.State);

            string strSQL = "insert into [users] ([username], firstname, lastname, email, [password]) values (?,?,?,?,?)";
            object returnVal;

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

            Comm.CommandText = "select [username] from [users] where [username] = ?";
            Comm.Parameters.AddWithValue("[username]", txtUserName.Text);
            returnVal = Comm.ExecuteScalar();
            if (returnVal == null)
            {
                Comm.Parameters.Clear();
                Comm.CommandText = strSQL;
                Comm.Parameters.AddWithValue("username", txtUserName.Text);
                Comm.Parameters.AddWithValue("firstname", txtFName.Text);
                Comm.Parameters.AddWithValue("lastname", txtLName.Text);
                Comm.Parameters.AddWithValue("email", txtEmail.Text);
                Comm.Parameters.AddWithValue("password", txtPassword.Text);
                Comm.ExecuteNonQuery();
            }
            else {
                Response.Write("Username already exists.");
            }
            Conn.Close();
            Conn = null;
        }
Beispiel #7
0
 public void insertImage(string wkImg)
 {
     System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
     cmd.CommandText = "Insert into [" + TableName + "] (imageName) values('" + wkImg + "')  ";
        cmd.Connection = conn;
         cmd.ExecuteNonQuery();
 }
Beispiel #8
0
        public static IDbCommand CreateCommand(EnumProviders provider)
        {
            IDbCommand cmd;

            switch (provider)
            {
                case EnumProviders.SqlServer:
                    cmd = new System.Data.SqlClient.SqlCommand();
                    break;
                case EnumProviders.OleDb:
                    cmd = new System.Data.OleDb.OleDbCommand();
                    break;
                case EnumProviders.Odbc:
                    cmd = new System.Data.Odbc.OdbcCommand();
                    break;
                case EnumProviders.Oracle:
                    throw new NotImplementedException("Provider not implemented");
                    break;
                default:
                    cmd = new System.Data.SqlClient.SqlCommand();
                    break;
            }

            return cmd;
        }
Beispiel #9
0
 /// <summary>
 /// M�todo necesario para admitir el Dise�ador, no se puede modificar
 /// el contenido del m�todo con el editor de c�digo.
 /// </summary>
 private void InitializeComponent()
 {
     System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
     this.oleDbDataAdapter1 = new System.Data.OleDb.OleDbDataAdapter();
     this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
     this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
     this.datosInforme1 = new informe_1.datosInforme();
     ((System.ComponentModel.ISupportInitialize)(this.datosInforme1)).BeginInit();
     //
     // oleDbDataAdapter1
     //
     this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1;
     this.oleDbDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
                                                                                                 new System.Data.Common.DataTableMapping("Table", "Table", new System.Data.Common.DataColumnMapping[] {
                                                                                                                                                                                                          new System.Data.Common.DataColumnMapping("NOMBRE", "NOMBRE")})});
     //
     // oleDbSelectCommand1
     //
     this.oleDbSelectCommand1.CommandText = "SELECT \'\' AS NOMBRE FROM DUAL";
     this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
     //
     // oleDbConnection1
     //
     this.oleDbConnection1.ConnectionString = ((string)(configurationAppSettings.GetValue("cadenaConexion", typeof(string))));
     //
     // datosInforme1
     //
     this.datosInforme1.DataSetName = "datosInforme";
     this.datosInforme1.Locale = new System.Globalization.CultureInfo("es-ES");
     this.datosInforme1.Namespace = "http://www.tempuri.org/datosInforme.xsd";
     this.Load += new System.EventHandler(this.Page_Load);
     ((System.ComponentModel.ISupportInitialize)(this.datosInforme1)).EndInit();
 }
Beispiel #10
0
        public static void makeAll(System.String baseDirectory, System.String version)
        {
            //make base directory
            if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
            {
                baseDirectory = baseDirectory + "/";
            }
            System.IO.FileInfo targetDir = SourceGenerator.makeDirectory(baseDirectory + PackageManager.GetVersionPackagePath(version) + "EventMapping");

            //get list of data types
            System.Data.OleDb.OleDbConnection conn = NormativeDatabase.Instance.Connection;
            System.String sql = "SELECT * from HL7EventMessageTypes inner join HL7Versions on HL7EventMessageTypes.version_id = HL7Versions.version_id where HL7Versions.hl7_version = '" + version + "'";
            System.Data.OleDb.OleDbCommand temp_OleDbCommand = new System.Data.OleDb.OleDbCommand();
            temp_OleDbCommand.Connection = conn;
            temp_OleDbCommand.CommandText = sql;
            System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();

            using (StreamWriter sw = new StreamWriter(targetDir.FullName + @"\EventMap.properties", false))
            {
                sw.WriteLine("#event -> structure map for " + version);
                while (rs.Read())
                {
                    string messageType = string.Format("{0}_{1}", rs["message_typ_snd"], rs["event_code"]);
                    string structure = (string) rs["message_structure_snd"];

                    sw.WriteLine(string.Format("{0} {1}", messageType, structure));
                }
            }
        }
Beispiel #11
0
            public void DBSetup()
            {
                // +++++++++++++++++++++++++++  DBSetup function +++++++++++++++++++++++++++
                // This DBSetup() method instantiates all the DB objects needed to access a DB, 
                // including OleDbDataAdapter, which contains 4 other objects(OlsDbSelectCommand, 
                // oleDbInsertCommand, oleDbUpdateCommand, oleDbDeleteCommand.) And each
                // Command object contains a Connection object and an SQL string object.
                OleDbDataAdapter2 = new System.Data.OleDb.OleDbDataAdapter();
                OleDbSelectCommand2 = new System.Data.OleDb.OleDbCommand();
                OleDbInsertCommand2 = new System.Data.OleDb.OleDbCommand();
                OleDbUpdateCommand2 = new System.Data.OleDb.OleDbCommand();
                OleDbDeleteCommand2 = new System.Data.OleDb.OleDbCommand();
                OleDbConnection2 = new System.Data.OleDb.OleDbConnection();

                OleDbDataAdapter2.DeleteCommand = OleDbDeleteCommand2;
                OleDbDataAdapter2.InsertCommand = OleDbInsertCommand2;
                OleDbDataAdapter2.SelectCommand = OleDbSelectCommand2;
                OleDbDataAdapter2.UpdateCommand = OleDbUpdateCommand2;

                // The highlighted text below should be changed to the location of your own database

                OleDbConnection2.ConnectionString = "Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Reg" + "istry Path =; Jet OLEDB:Database L" +
                "ocking Mode=1;Data Source= C:\\Users\\Trenton MCleod\\Desktop\\RegistrationDB.mdb;J" +
                "et OLEDB:Engine Type=5;Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:System datab" +
                "ase=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Mode=S" +
                "hare Deny None;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet " +
                "OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repai" +
                "r=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1";

            }  //end DBSetup()
Beispiel #12
0
        public int AddEvent(String eventName, String eventRoom,
			String eventAttendees, String eventDate)
        {
            System.Data.OleDb.OleDbConnection oleDbConnection1;
            System.Data.OleDb.OleDbDataAdapter daEvents;
            DataSet ds;

            oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
            oleDbConnection1.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=C:\\Inetpub\\wwwroot\\PCSWebApp3\\PCSWebApp3.mdb";
            String oleDbCommand = "INSERT INTO Events (Name, Room, AttendeeList," +
                " EventDate) VALUES ('" + eventName + "', '" +
                eventRoom + "', '" + eventAttendees + "', '" +
                eventDate + "')";
            System.Data.OleDb.OleDbCommand insertCommand =
                new System.Data.OleDb.OleDbCommand(oleDbCommand,
                oleDbConnection1);
            oleDbConnection1.Open();

            int queryResult = insertCommand.ExecuteNonQuery();
            if (queryResult == 1)
            {
                daEvents = new System.Data.OleDb.OleDbDataAdapter(
                    "SELECT * FROM Events", oleDbConnection1);
                ds = (DataSet)Application["ds"];
                ds.Tables["Events"].Clear();
                daEvents.Fill(ds, "Events");
                Application.Lock();
                Application["ds"] = ds;
                Application.UnLock();
                oleDbConnection1.Close();
            }
            return queryResult;
        }
Beispiel #13
0
        public virtual int FillByWhereClause(AccountDataset.AccountsDataTable dataTable, string whereClause, System.Data.OleDb.OleDbParameter[] parameters)
        {
            System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
            command.Connection = this.Connection;
            command.CommandText = @"select * from
            (Select ""C-"" & CustomerID as ID, ""Customer"" AS CustomerSupplierFlag,
            CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax, '' as HomePage, CreateID, CreateUser, ModifyID,  ModifyUser

             from Customers
            Union
            Select ""S-"" &  SupplierID as ID, ""Supplier"" AS CustomerSupplierFlag,

            CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax, HomePage, CreateID, CreateUser, ModifyID,  ModifyUser
            FROM         Suppliers) as a "
            + whereClause + ";";
            command.CommandType = System.Data.CommandType.Text;

            if (null != parameters)
                command.Parameters.AddRange(parameters);

            this.Adapter.SelectCommand = command;
            if ((this.ClearBeforeFill == true))
            {
                dataTable.Clear();
            }
            int returnValue = this.Adapter.Fill(dataTable);
            return returnValue;
        }
Beispiel #14
0
        /// <summary>
        /// Create access database file
        /// </summary>
        public static void create_mdb_file(DataSet ds, string destination, string template)
        {
            if(SqlConvert.ToString(template) == "")
                throw new Err("You must specify the location of a template mdb file inherit from.");
            if(!System.IO.File.Exists(template))
                throw new Err("The specified template file \"" + template + "\" could not be found.");
            if(SqlConvert.ToString(destination) == "")
                throw new Err("You must specify the destination location and filename of the mdb file to create.");

            //COPY THE TEMPLATE AND CREATE DESTINATION FILE
            System.IO.File.Copy(template,destination,true);
            //CONNECT TO THE DESTINATION FILE
            string sconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + destination + ";";
            System.Data.OleDb.OleDbConnection oconn = new System.Data.OleDb.OleDbConnection(sconn);
            oconn.Open();
            System.Data.OleDb.OleDbCommand ocmd = new System.Data.OleDb.OleDbCommand();
            ocmd.Connection = oconn;
            //WRITE TO THE DESTINATION FILE
            try
            {
                oledb.insert_dataset(ds,ocmd);
            }
            catch(Exception ex)
            {
                //System.Web.HttpContext.Current.Response.Write(ex.ToString());
                General.Debugging.Report.SendError("Error exporting to MS Access", ex.ToString() + "\r\n\r\n\r\n" + ocmd.CommandText);
            }
            finally
            {
                // Close the connection.
                oconn.Close();
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {   // Botão btnResultados
            try
            {
                string id1 = txtIdade1.Text;
                string id2 = txtIdade2.Text;
                string strSsexo = "";
                if (rbMasculino.Checked) strSsexo = " sexo = 'M' AND ";
                    else if (rbFeminino.Checked) strSsexo = " sexo = 'F' AND ";
                        else strSsexo = "";

                sql = "select * from alunos WHERE " + strSsexo 
                    + " idade>=" + id1 + " AND idade<=" + id2 
                    + " ORDER BY nome";
                stm = new System.Data.OleDb.OleDbCommand(sql, conexao);
                rs = stm.ExecuteReader();
                string strSaida = "";
                while (rs.Read())
                {
                    string dados = "RGM: " + rs.GetString(0) 
                        + ", " + rs.GetString(1) + ", idade: " + rs.GetInt32(3)
                        + ", sexo: " + rs.GetString(4)
                        + ", curso: " + rs.GetString(2);
                    strSaida += dados + "\r\n";
                }
                txtResultados.Text = strSaida;
            }
            catch (Exception exsql) { MessageBox.Show("Erro na consulta"); }
            if(stm!=null)stm.Dispose();
            if(rs!=null)rs.Close();
        }
Beispiel #16
0
        public static bool AnalyzeExcel(ExcelXMLLayout layout)
        {
            System.Data.OleDb.OleDbConnection conn = null;
            try
            {
                conn = new System.Data.OleDb.OleDbConnection(MakeConnectionString(layout.solution.path));

                conn.Open();
                System.Data.DataTable table = conn.GetOleDbSchemaTable(
                    System.Data.OleDb.OleDbSchemaGuid.Columns,
                    new object[] { null, null, layout.sheet + "$", null });

                layout.Clear();
                System.Diagnostics.Debug.WriteLine("Start Analyze [" + table.Rows.Count + "]");

                foreach (System.Data.DataRow row in table.Rows)
                {
                    string name = row["Column_Name"].ToString();

                    System.Diagnostics.Debug.WriteLine(name);

                    // 测试数据类型
                    ExcelXMLLayout.KeyType testType = ExcelXMLLayout.KeyType.Unknown;
                    {
                        System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(
                            string.Format("select [{0}] from [{1}$]", name, layout.sheet), conn
                            );
                        System.Data.OleDb.OleDbDataReader r = cmd.ExecuteReader();
                        while (r.Read())
                        {
                            System.Diagnostics.Debug.WriteLine(r[0].GetType());
                            if (r[0].GetType() == typeof(System.Double))
                            {
                                testType = ExcelXMLLayout.KeyType.Integer;
                                break;
                            }
                            if (testType == ExcelXMLLayout.KeyType.String)
                            {
                                break;
                            }
                            testType = ExcelXMLLayout.KeyType.String;
                        }
                        r.Close();
                        cmd.Dispose();
                    }

                    layout.Add(name, testType);
                }
                table.Dispose();
                conn.Close();

                return true;
            }
            catch (Exception outErr)
            {
                lastError = string.Format("无法分析,Excel 无法打开\r\n{0}", outErr.Message);
            }
            return false;
        }
Beispiel #17
0
 public string getRowCount()
 {
     string query = "select * from [" + TableName + "]";
     System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
     System.Data.OleDb.OleDbDataReader dr = cmd.ExecuteReader();
     DataTable dt = new DataTable();
     dataTable.Load(dr);
     dr.Close();
     return dataTable.Rows.Count.ToString();
 }
 public static System.Data.OleDb.OleDbCommand Comando(string sql, params object[] args)
 {
     System.Data.OleDb.OleDbCommand com = new System.Data.OleDb.OleDbCommand(sql, cnx);
     for (System.Int32 i = 0; i < args.Length; i++)
     {
         System.Data.OleDb.OleDbParameter par = new System.Data.OleDb.OleDbParameter("DPeriodo_" + i, args[i]);
         com.Parameters.Add(par);
     }
     return com;
 }
Beispiel #19
0
 private void m_select()
 {
     this.oDS = new DataSet();
     this.rq_sql = "SELECT * FROM TB_PERSONNE;";                              //Requête SELECT Paramétrée
     this.oCMD = new System.Data.OleDb.OleDbCommand(this.rq_sql, this.oCNX);  //Création d'un objet commande qui prend en paramètre la requête SQL et la l'objet de Connexion a la BDD.
     this.oDA = new System.Data.OleDb.OleDbDataAdapter(this.oCMD);            //Création d'un objet DataAdapter qui prend en paramètre l'objet commande. (DataAdapter et l'interface réel entre l'application et la BDD.
     this.oDA.Fill(this.oDS, "personne");                                     //Execution de la requête SQL, si retournes des enregistrements, elle sont placé dans l'objet DataSet, dans la DataTable "Personne".
     this.dataGridView1.DataSource = this.oDS;                                //On attribue le modèle de mon DataSet au gridview pour afficher mes enregistrement.
     this.dataGridView1.DataMember = "personne";                              //Mais bien définir la table a afficher, car le DataSet peut en contenir plusieur.
 }
Beispiel #20
0
 //##########################################################
 //#            Changer l'emplacement de la BDD             #
 //##########################################################
 private void Form1_Load()
 {
     this.rq_sql = null;
                                                                   //Changer l'emplacement ou ce trouve votre BDD
     this.cnx = @"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Orage\Documents\Visual Studio 2015\Projects\AppBaseDeDonnee\AppBaseDeDonnee\MyBDD.mdb";
     this.oCNX = new System.Data.OleDb.OleDbConnection(this.cnx);  
     this.oCMD = null;
     this.oDA = null;
     this.oDS = new DataSet();
     this.m_select();
 }
Beispiel #21
0
        public DataSet Method1()
        {
            string s = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("Northwind1.mdb") + ";Persist Security Info=False";
            string z = "select * from Клиенты";
            System.Data.OleDb.OleDbConnection olcon = new System.Data.OleDb.OleDbConnection(s);
            System.Data.OleDb.OleDbCommand olcom = new System.Data.OleDb.OleDbCommand(z, olcon);
            System.Data.OleDb.OleDbDataAdapter DA = new System.Data.OleDb.OleDbDataAdapter(olcom);
            System.Data.DataSet DS = new System.Data.DataSet();
            DA.Fill(DS);

            return DS;
        }
 public System.Data.DataTable Read(string filename)
 {
     var excelDataAdapter = new System.Data.OleDb.OleDbDataAdapter();
     _connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + filename + "; Extended Properties = Excel 8.0;";
     var excelConn = new System.Data.OleDb.OleDbConnection(_connectionString);
     excelConn.Open();
     var dtProtocol = new System.Data.DataTable { TableName = "Protocol" };
     var excelCommand = new System.Data.OleDb.OleDbCommand("SELECT * FROM [протокол плавки$]", excelConn);
     excelDataAdapter.SelectCommand = excelCommand;
     excelDataAdapter.Fill(dtProtocol);
     excelConn.Close();
     return dtProtocol;
 }
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.dgNotes = new System.Windows.Forms.DataGrid();
     this.daJoin = new System.Data.OleDb.OleDbDataAdapter();
     this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
     this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
     ((System.ComponentModel.ISupportInitialize)(this.dgNotes)).BeginInit();
     this.SuspendLayout();
     //
     // dgNotes
     //
     this.dgNotes.DataMember = "";
     this.dgNotes.HeaderForeColor = System.Drawing.SystemColors.ControlText;
     this.dgNotes.Location = new System.Drawing.Point(16, 16);
     this.dgNotes.Name = "dgNotes";
     this.dgNotes.Size = new System.Drawing.Size(744, 336);
     this.dgNotes.TabIndex = 0;
     //
     // daJoin
     //
     this.daJoin.SelectCommand = this.oleDbSelectCommand1;
     this.daJoin.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
                                                                                      new System.Data.Common.DataTableMapping("Table", "Notes", new System.Data.Common.DataColumnMapping[] {
                                                                                                                                                                                               new System.Data.Common.DataColumnMapping("primulatext", "primulatext"),
                                                                                                                                                                                               new System.Data.Common.DataColumnMapping("visitnote", "visitnote"),
                                                                                                                                                                                               new System.Data.Common.DataColumnMapping("noteid", "noteid"),
                                                                                                                                                                                               new System.Data.Common.DataColumnMapping("primula", "primula")})});
     this.daJoin.RowUpdated += new System.Data.OleDb.OleDbRowUpdatedEventHandler(this.oleDbDataAdapter1_RowUpdated);
     //
     // oleDbConnection1
     //
     this.oleDbConnection1.ConnectionString = @"Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Database Password=;Data Source=""C:\Documents and Settings\Anders Ruberg\Mina dokument\Visual Studio Projects\RehabLight\bin\Debug\rehab.mdb"";Password=;Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;Mode=Share Deny None;Jet OLEDB:New Database Password=;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;User ID=Admin;Jet OLEDB:Encrypt Database=False";
     //
     // oleDbSelectCommand1
     //
     this.oleDbSelectCommand1.CommandText = "SELECT Charges.primulatext, Notes.visitnote, Notes.noteid, Notes.primula FROM (No" +
         "tes INNER JOIN Charges ON Charges.chargeid = Notes.chargeid) WHERE (Notes.primul" +
         "a = FALSE) AND (Notes.visitnote = TRUE) AND (MID([Notes.visitdatetime], 1, 4) = " +
         "\'2007\')";
     this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
     //
     // FilteredNotes
     //
     this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
     this.ClientSize = new System.Drawing.Size(768, 390);
     this.Controls.Add(this.dgNotes);
     this.Name = "FilteredNotes";
     this.Text = "FilteredNotes";
     ((System.ComponentModel.ISupportInitialize)(this.dgNotes)).EndInit();
     this.ResumeLayout(false);
 }
Beispiel #24
0
        public void UpdateDateTime(string skey, DateTime StartDatetime, DateTime updatetime)
        {
            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
            string Query = "Update [" + TableName + "] set submittedOn = '" + StartDatetime.ToString("dd/MM/yyyy hh:mm:ss") + "' ";
            if (updatetime.Year > 1900)
            {
                Query += ", lastEdited = '" + updatetime.ToString("dd/MM/yyyy hh:mm:ss") + "'";
                            }

            Query += " Where imagePath = '" + skey + "'";
            cmd.CommandText = Query;
            cmd.Connection = conn;
               int x =  cmd.ExecuteNonQuery();
        }
Beispiel #25
0
 /// <summary>
 /// M�todo necesario para admitir el Dise�ador, no se puede modificar
 /// el contenido del m�todo con el editor de c�digo.
 /// </summary>
 private void InitializeComponent()
 {
     System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
     this.oleDbDataAdapter1 = new System.Data.OleDb.OleDbDataAdapter();
     this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
     this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
     this.contrato1 = new reporte_contrato.contrato();
     ((System.ComponentModel.ISupportInitialize)(this.contrato1)).BeginInit();
     //
     // oleDbDataAdapter1
     //
     this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1;
     this.oleDbDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
                                                                                                 new System.Data.Common.DataTableMapping("Table", "contrato", new System.Data.Common.DataColumnMapping[] {
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("NOMBRE_INSTITUCION", "NOMBRE_INSTITUCION"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("RUT_INSTITUCION", "RUT_INSTITUCION"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("RUT_POSTULANTE", "RUT_POSTULANTE"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("EDAD", "EDAD"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("NOMBRE_ALUMNO", "NOMBRE_ALUMNO"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("CARRERA", "CARRERA"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("RUT_CODEUDOR", "RUT_CODEUDOR"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("NOMBRE_CODEUDOR", "NOMBRE_CODEUDOR"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("DIRECCION", "DIRECCION"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("CIUDAD", "CIUDAD"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("COMUNA", "COMUNA"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("TIPO_DOCUMENTO", "TIPO_DOCUMENTO"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("DOCUMENTO", "DOCUMENTO"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("NOMBRE_BANCO", "NOMBRE_BANCO"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("VALOR_DOCTO", "VALOR_DOCTO"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("FECHA_VENCIMIENTO", "FECHA_VENCIMIENTO"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("TOTAL_M", "TOTAL_M"),
                                                                                                                                                                                                             new System.Data.Common.DataColumnMapping("TOTAL_A", "TOTAL_A")})});
     //
     // oleDbSelectCommand1
     //
     this.oleDbSelectCommand1.CommandText = @"SELECT '' AS NOMBRE_INSTITUCION, '' AS RUT_INSTITUCION, '' AS RUT_POSTULANTE, '' AS EDAD, '' AS NOMBRE_ALUMNO, '' AS CARRERA, '' AS RUT_CODEUDOR, '' AS NOMBRE_CODEUDOR, '' AS DIRECCION, '' AS CIUDAD, '' AS COMUNA, '' AS TIPO_DOCUMENTO, '' AS DOCUMENTO, '' AS NOMBRE_BANCO, '' AS VALOR_DOCTO, '' AS FECHA_VENCIMIENTO, '' AS TOTAL_M, '' AS TOTAL_A FROM DUAL";
     this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
     //
     // oleDbConnection1
     //
     this.oleDbConnection1.ConnectionString = ((string)(configurationAppSettings.GetValue("cadenaConexion", typeof(string))));
     //
     // contrato1
     //
     this.contrato1.DataSetName = "contrato";
     this.contrato1.Locale = new System.Globalization.CultureInfo("es-ES");
     this.contrato1.Namespace = "http://www.tempuri.org/contrato.xsd";
     this.Load += new System.EventHandler(this.Page_Load);
     ((System.ComponentModel.ISupportInitialize)(this.contrato1)).EndInit();
 }
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
			this.oleDbCommand1 = new System.Data.OleDb.OleDbCommand();
			// 
			// oleDbConnection1
			// 
			this.oleDbConnection1.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=C:\Inetpub\wwwroot\CSharpBook\nwind.mdb;Mode=Share Deny None;Extended Properties="""";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password="""";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False";
			// 
			// oleDbCommand1
			// 
			this.oleDbCommand1.Connection = this.oleDbConnection1;
			this.Load += new System.EventHandler(this.Page_Load);

		}
        public void AttemptReadingDBFWithOLEDB()
        {
            //FeatureLayer target = new MapPolygonLayer();
            string filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "soils.shp");
            string dBaseFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles");

            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source = " + dBaseFile + ";Extended Properties =dBase IV;";
            System.Data.OleDb.OleDbConnection dBaseConnection;
            dBaseConnection = new System.Data.OleDb.OleDbConnection(connectionString);
            dBaseConnection.Open();
            System.Data.OleDb.OleDbCommand dBaseCommand;
            dBaseCommand = new System.Data.OleDb.OleDbCommand("SELECT * FROM [soils]", dBaseConnection);
            System.Data.OleDb.OleDbDataReader dBaseDataReader;
            dBaseDataReader = dBaseCommand.ExecuteReader(CommandBehavior.SequentialAccess);
        }
Beispiel #28
0
        private void btnGo_Click(object sender, EventArgs e)
        {
            lblError.Text = "";
            //open connection to database

            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
            conn.ConnectionString = txtConnString.Text;
            conn.Open();
            // MessageBox.Show(conn.State.ToString());
            //create my command
            System.Data.OleDb.OleDbCommand comm = new System.Data.OleDb.OleDbCommand();
            comm.Connection = conn;
            //send the sql through the command
            comm.CommandText = txtSQL.Text;

            //receive the result into a data container.

            System.Data.OleDb.OleDbDataReader dr;
            try
            {

                if (txtSQL.Text.ToUpper().StartsWith("SELECT"))
                {
                    dr = comm.ExecuteReader();
                    System.Data.DataTable dt = new DataTable();
                    dt.Load(dr);
                    Grid1.AutoGenerateColumns = true;
                    //bind the result to the grid

                    Grid1.DataSource = dt;
                }
                else
                {
                    MessageBox.Show(comm.ExecuteNonQuery().ToString());
                }

            }
            catch (Exception ex)
            {

                lblError.Text = ex.Message;
            }
            finally
            {
                conn.Close();

            }
        }
Beispiel #29
0
 private void toolStripButton2_Click(object sender, EventArgs e)
 {
     try
     {
         if (grvKQ.RowCount > 0)
         {
             if (kt(MtbNTDG.Text, cbtenphongb.Text) == "")
             {
                 for (int i = 0; i < grvKQ.RowCount; i++)
                 {
                     sql = "insert into theodoisk (ngaydanhgia,mahocsinh,sothangtuoi,cannang,chieucao,danhgia) values (@ngaydanhgia,@mahocsinh,@sothangtuoi,@cannang,@chieucao,@danhgia)";
                     System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
                     cmd.CommandText = sql;
                     cmd.Parameters.Add("@ngaydanhgia", System.Data.OleDb.OleDbType.Date).Value   = Convert.ToDateTime(MtbNTDG.Text);
                     cmd.Parameters.Add("@mahocsinh", System.Data.OleDb.OleDbType.VarChar).Value  = grvKQ.GetRowCellValue(i, colmshs);
                     cmd.Parameters.Add("@sothangtuoi", System.Data.OleDb.OleDbType.Double).Value = Connect.GetDou(grvKQ.GetRowCellValue(i, colsothangtuoi));
                     cmd.Parameters.Add("@cannang", System.Data.OleDb.OleDbType.Double).Value     = Connect.GetDou(grvKQ.GetRowCellValue(i, colcannang).ToString());
                     cmd.Parameters.Add("@chieucao", System.Data.OleDb.OleDbType.Double).Value    = Connect.GetDou(grvKQ.GetRowCellValue(i, colchieucao).ToString());
                     cmd.Parameters.Add("@danhgia", System.Data.OleDb.OleDbType.VarChar).Value    = Connect.GetStr(grvKQ.GetRowCellValue(i, coldanhgia));
                     KPBT.Modules.Connect.LuuDL(cmd);
                 }
             }
             else
             {
                 for (int i = 0; i < grvKQ.RowCount; i++)
                 {
                     sql = "update theodoisk set ngaydanhgia=@ngaydanhgia,mahocsinh=@mahocsinh,sothangtuoi=@sothangtuoi,cannang=@cannang,chieucao=@chieucao,danhgia=@danhgia" +
                           " where idtheodoisk =" + Convert.ToInt64(grvKQ.GetRowCellValue(i, colid).ToString());
                     System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
                     cmd.CommandText = sql;
                     cmd.Parameters.Add("@ngaydanhgia", System.Data.OleDb.OleDbType.Date).Value   = Convert.ToDateTime(MtbNTDG.Text);
                     cmd.Parameters.Add("@mahocsinh", System.Data.OleDb.OleDbType.VarChar).Value  = grvKQ.GetRowCellValue(i, colmshs);
                     cmd.Parameters.Add("@sothangtuoi", System.Data.OleDb.OleDbType.Double).Value = Connect.GetDou(grvKQ.GetRowCellValue(i, colsothangtuoi));
                     cmd.Parameters.Add("@cannang", System.Data.OleDb.OleDbType.Double).Value     = Connect.GetDou(grvKQ.GetRowCellValue(i, colcannang).ToString());
                     cmd.Parameters.Add("@chieucao", System.Data.OleDb.OleDbType.Double).Value    = Connect.GetDou(grvKQ.GetRowCellValue(i, colchieucao).ToString());
                     cmd.Parameters.Add("@danhgia", System.Data.OleDb.OleDbType.VarChar).Value    = Connect.GetStr(grvKQ.GetRowCellValue(i, coldanhgia));
                     KPBT.Modules.Connect.LuuDL(cmd);
                 }
             }
         }
         MessageBox.Show("Bạn đã lưu dữ liệu thành công!", "Thông báo");
     }
     catch
     {
         MessageBox.Show("Có lỗi trong quá trình lưu. Bạn hãy kiểm tra lại!", "Thông báo!");
     }
 }
Beispiel #30
0
        static void Main(string[] args)
        {
            string connstring =
            @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\DropBox\My Dropbox\Devry\CIS407\SU10B\day5\NorthWind.mdb;";
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
            string sql = "";
            System.Data.DataSet ds = new System.Data.DataSet();
            System.Data.OleDb.OleDbDataReader dr;
            System.Data.OleDb.OleDbCommand comm = new System.Data.OleDb.OleDbCommand();

            try
            {
                //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 = Console.ReadLine();
                comm.CommandText = sql;
                if (sql.ToLower().IndexOf("select") == 0)
                {
                    dr = comm.ExecuteReader();
                    while (dr.Read())
                    {
                        Console.WriteLine(dr.GetString(0));
                    }
                }
                else
                {
                    Console.WriteLine(comm.ExecuteNonQuery().ToString());
                }
            }
            catch ( Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
            finally
            {
                Console.ReadLine();
                comm.Dispose();
                conn.Close();
                conn = null;
            }
        }
        public void ReceivePayment()
        {
            System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection();
            con.ConnectionString =
                "Provider=Microsoft.Jet.OLEDB.4.0;"
                + "Data Source=acct.mdb;";
            con.Open();
            System.Data.OleDb.OleDbCommand com = new System.Data.OleDb.OleDbCommand();
            com.Connection  = con;
            com.CommandText = "INSERT INTO Income(accountid, company, firstName, lastName, [date], amount, invoiceNo, incomeNote, paymentMethod, checkNo, bankAccountNo, routingNo, theirbankAccountNo, theirroutingNo)VALUES(" + this.accountid + ", '" + companytb.Text.Replace("'", "''") + "','" + firstNametb.Text.Replace("'", "''") + "','" + lastnametb.Text.Replace("'", "''") + "','" + datetb.Text + "'," + amounttb.Text + ",'" + invoiceNotb.Text.Replace("'", "''") + "', '" + incomeNotetb.Text.Replace("'", "''") + "', '" + paymentMethodcb.Text.Replace("'", "''") + "', '" + checkNotb.Text.Replace("'", "''") + "', '" + mybankacctnotb.Text.Replace("'", "''") + "', '" + myroutingnotb.Text.Replace("'", "''") + "', '" + theirbankacctnotb.Text.Replace("'", "''") + "', '" + theirroutingnotb.Text.Replace("'", "''") + "')";
            com.ExecuteNonQuery();
            com.CommandText = "Delete From AcctAR Where id=" + this.arId + " and accountid=" + this.accountid;
            com.ExecuteNonQuery();
            MessageBox.Show("Done");

            con.Close();
        }
        public override System.Data.DataColumn[] ObtenerColumnas(FuenteInformacion fuenteInformacion, string rutaArchivo)
        {
            try
            {
                DataSet dsMsExcel = new DataSet();
                using (System.Data.OleDb.OleDbConnection objOleConnection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + rutaArchivo + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'"))
                {
                    System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
                    objOleConnection.Open();
                    DataTable worksheets = objOleConnection.GetSchema("Tables");
                    string    hoja       = worksheets.Rows[0][2].ToString();
                    System.Data.OleDb.OleDbCommand select = new System.Data.OleDb.OleDbCommand("SELECT  * FROM [" + hoja + "]", objOleConnection);
                    select.CommandType    = CommandType.Text;
                    adapter.SelectCommand = select;
                    dsMsExcel.Tables.Clear();
                    adapter.Fill(dsMsExcel);
                    if (dsMsExcel.Tables.Count > 0)
                    {
                        DataRow      col      = dsMsExcel.Tables[0].Rows[0];
                        DataColumn[] columnas = new DataColumn[col.ItemArray.Length];
                        int          index    = 0;
                        string       nombre;
                        foreach (object campo in col.ItemArray)
                        {
                            if (!string.IsNullOrEmpty(campo.ToString()))
                            {
                                nombre = campo.ToString().Trim();
                            }
                            else
                            {
                                nombre = "NULL" + index.ToString();
                            }

                            columnas[index] = new DataColumn(nombre);
                            index++;
                        }
                        return(columnas);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(null);
        }
Beispiel #33
0
        public System.Data.DataSet ReadExcelFile(String filename)
        {
            // Create connection string variable.
            String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                       "Data Source=" + Server.MapPath("~/Images/" + filename) + ";" +
                                       "Extended Properties=Excel 8.0;";

            // Create connection object
            System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(sConnectionString);

            // Open connection with the database.
            objConn.Open();

            // The code to follow uses a SQL SELECT command to display the data from the worksheet.

            // Create new OleDbCommand to return data from worksheet.
            System.Data.OleDb.OleDbCommand objCmdSelect = new System.Data.OleDb.OleDbCommand("SELECT * FROM [Products$]", objConn);

            // Create new OleDbDataAdapter that is used to build a DataSet
            // based on the preceding SQL SELECT statement.
            System.Data.OleDb.OleDbDataAdapter objAdapter1 = new System.Data.OleDb.OleDbDataAdapter();

            // Pass the Select command to the adapter.
            objAdapter1.SelectCommand = objCmdSelect;

            // Create new DataSet to hold information from the worksheet.
            System.Data.DataSet objDataset1 = new System.Data.DataSet();
            try
            {
                // Fill the DataSet with the information from the worksheet.
                objAdapter1.Fill(objDataset1, "Products");
            }
            catch (Exception exp)
            {
                objConn.ResetState();
                objConn.Dispose();
                objConn.Close();
            }
            //objConn.Dispose();
            // Clean up objects.

            objConn.Close();


            return(objDataset1);
        }
Beispiel #34
0
        private static List <List <string> > File_Selected_New(FileInfo _file)
        {
            DataSet ds = new DataSet();
            string  connectionString = GetConnectionString(_file);

            using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString))
            {
                conn.Open();
                System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
                cmd.Connection = conn;

                // Get all Sheets in Excel File
                DataTable dtSheet = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);

                // Loop through all Sheets to get data
                foreach (DataRow dr in dtSheet.Rows)
                {
                    string sheetName = dr["TABLE_NAME"].ToString();

                    // Get all rows from the Sheet
                    cmd.CommandText = "SELECT * FROM [" + sheetName + "]";

                    DataTable dt = new DataTable();
                    dt.TableName = sheetName;

                    System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(cmd);
                    da.Fill(dt);

                    ds.Tables.Add(dt);
                }

                // В list_table хранится информация по строкам, начиная с [0]
                List <List <string> > list_table = new List <List <string> >();
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                {
                    List <string> list_row = new List <string>();
                    for (int i = 1; i < ds.Tables[0].Rows.Count; i++)
                    {
                        list_row.Add(ds.Tables[0].Rows[i].ItemArray[j].ToString());
                    }
                    list_table.Add(list_row);
                }

                return(list_table);
            }
        }
        /// <summary>
        /// method when the search button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string searchstring = search.Text;

            System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\ASD\ase 2\user Database.accdb");
            connection.Open();                                                                                                                                            //opens connection

            string query = "Select [code ID], [user], [class], [method], [line], [solution], [time added] FROM fixed_code WHERE [code ID] LIKE '%" + searchstring + "%'"; //query that searches the fixed code where the code id is like the search string

            System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, connection);
            cmd.CommandType = CommandType.Text;
            System.Data.OleDb.OleDbDataAdapter myDataAdapter = new System.Data.OleDb.OleDbDataAdapter(cmd);
            DataTable fixed_code = new DataTable();

            myDataAdapter.Fill(fixed_code);        //fills datagrid with search results
            dataGridView1.DataSource = fixed_code; //assigns the data source
        }
Beispiel #36
0
        private void button3_Click(object sender, EventArgs e)
        {   // Botão btnResultados
            try
            {
                string id1      = txtIdade1.Text;
                string id2      = txtIdade2.Text;
                string strSsexo = "";
                if (rbMasculino.Checked)
                {
                    strSsexo = " sexo = 'M' AND ";
                }
                else if (rbFeminino.Checked)
                {
                    strSsexo = " sexo = 'F' AND ";
                }
                else
                {
                    strSsexo = "";
                }

                sql = "select * from alunos WHERE " + strSsexo
                      + " idade>=" + id1 + " AND idade<=" + id2
                      + " ORDER BY nome";
                stm = new System.Data.OleDb.OleDbCommand(sql, conexao);
                rs  = stm.ExecuteReader();
                string strSaida = "";
                while (rs.Read())
                {
                    string dados = "RGM: " + rs.GetString(0)
                                   + ", " + rs.GetString(1) + ", idade: " + rs.GetInt32(3)
                                   + ", sexo: " + rs.GetString(4)
                                   + ", curso: " + rs.GetString(2);
                    strSaida += dados + "\r\n";
                }
                txtResultados.Text = strSaida;
            }
            catch (Exception exsql) { MessageBox.Show("Erro na consulta"); }
            if (stm != null)
            {
                stm.Dispose();
            }
            if (rs != null)
            {
                rs.Close();
            }
        }
Beispiel #37
0
 /// <summary>
 /// Método necesario para admitir el Diseñador, no se puede modificar
 /// el contenido del método con el editor de código.
 /// </summary>
 private void InitializeComponent()
 {
     System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
     this.oleDbConnection1    = new System.Data.OleDb.OleDbConnection();
     this.oleDbDataAdapter1   = new System.Data.OleDb.OleDbDataAdapter();
     this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
     this.dataSet11           = new procedencia.DataSet1();
     ((System.ComponentModel.ISupportInitialize)(this.dataSet11)).BeginInit();
     //
     // oleDbConnection1
     //
     this.oleDbConnection1.ConnectionString = ((string)(configurationAppSettings.GetValue("cadenaConexion", typeof(string))));
     //
     // oleDbDataAdapter1
     //
     this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1;
     this.oleDbDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
         new System.Data.Common.DataTableMapping("Table", "T_Datos", new System.Data.Common.DataColumnMapping[] {
             new System.Data.Common.DataColumnMapping("ANO", "ANO"),
             new System.Data.Common.DataColumnMapping("SEDE_TDESC", "SEDE_TDESC"),
             new System.Data.Common.DataColumnMapping("CARR_TDESC", "CARR_TDESC"),
             new System.Data.Common.DataColumnMapping("JORN_TDESC", "JORN_TDESC"),
             new System.Data.Common.DataColumnMapping("COLEGIO_EGRESO", "COLEGIO_EGRESO"),
             new System.Data.Common.DataColumnMapping("CIUD_TDESC", "CIUD_TDESC"),
             new System.Data.Common.DataColumnMapping("TCOL_TDESC", "TCOL_TDESC"),
             new System.Data.Common.DataColumnMapping("ALUMNOS", "ALUMNOS"),
             new System.Data.Common.DataColumnMapping("PSU", "PSU")
         })
     });
     this.oleDbDataAdapter1.RowUpdated += new System.Data.OleDb.OleDbRowUpdatedEventHandler(this.oleDbDataAdapter1_RowUpdated);
     //
     // oleDbSelectCommand1
     //
     this.oleDbSelectCommand1.CommandText = "SELECT \'\' AS ANO, \'\' AS SEDE_TDESC, \'\' AS CARR_TDESC, \'\' AS JORN_TDESC, \'\' AS COL" +
                                            "EGIO_EGRESO, \'\' AS CIUD_TDESC, \'\' AS TCOL_TDESC, \'\' AS ALUMNOS, \'\' AS PSU FROM D" +
                                            "UAL";
     this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
     //
     // dataSet11
     //
     this.dataSet11.DataSetName = "DataSet1";
     this.dataSet11.Locale      = new System.Globalization.CultureInfo("es-CL");
     this.dataSet11.Namespace   = "http://www.tempuri.org/DataSet1.xsd";
     this.Load += new System.EventHandler(this.Page_Load);
     ((System.ComponentModel.ISupportInitialize)(this.dataSet11)).EndInit();
 }
Beispiel #38
0
        public bool DeleteQry(string strCommand)
        {
            try
            {
                System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(dbConnection);
                conn.Open();
                System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(strCommand, conn);
                cmd.ExecuteNonQuery();
                conn.Close();
            }
            catch (Exception)
            {
                return(true);
            }

            return(false);
        }
Beispiel #39
0
        private void m_axCalendar_DoCreateRPattern(object sender, AxXtremeCalendarControl._DCalendarControlEvents_DoCreateRPatternEvent e)
        {
            e.bResult = false;

            if (!IsOpen())
            {
                return;
            }

            try
            {
                String strSQL = "SELECT * FROM CalendarRecurrencePatterns WHERE RecurrencePatternID = 0 ";

                System.Data.OleDb.OleDbDataAdapter    oleDbDataAdapter = new System.Data.OleDb.OleDbDataAdapter(strSQL, m_oleDbConnection);
                System.Data.OleDb.OleDbCommandBuilder custCB           = new System.Data.OleDb.OleDbCommandBuilder(oleDbDataAdapter);
                custCB.QuotePrefix = "[";
                custCB.QuoteSuffix = "]";

                System.Data.DataSet objPatternDSet = new System.Data.DataSet();
                oleDbDataAdapter.Fill(objPatternDSet);

                //code to modify data in dataset here
                System.Data.DataRow objDRow = objPatternDSet.Tables[0].NewRow();
                objPatternDSet.Tables[0].Rows.Add(objDRow);

                m_DataHelper.PutRPatternToData(e.pPattern, objDRow);

                oleDbDataAdapter.Update(objPatternDSet);

                //'-- update Auto EventID
                System.Data.OleDb.OleDbCommand objCommand = m_oleDbConnection.CreateCommand();
                objCommand.CommandText = "SELECT MAX(RecurrencePatternID) AS NewNewPatternID FROM CalendarRecurrencePatterns";
                System.Data.OleDb.OleDbDataReader objReader = objCommand.ExecuteReader();
                objReader.Read();

                e.newPatternID = objReader.GetInt32(0);

                objReader.Close();

                e.bResult = true;
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("EXCEPTION! providerSQLServer.m_axCalendar_DoCreateRPattern: " + ex.Message);
            }
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to Update all the records", "TareEntry", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                DataTable resultData = (DataTable)dgRakeView.DataSource;

                string query = string.Format("Select ID,Slno,RakeNo,WagonNo,WagonType,Tare,Gross,dateout,timeout,spd,PCC,[From],[Product],[To],Net,UL,OL,CC from Temp where RakeNo={0} order by val(Slno)", txtRakeNo.Text);
                var    db    = new DBEngine();
                btnUpdate.Visible = false;
                var dt = new System.Data.DataTable();
                System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection(db.ConnectionString);

                System.Data.OleDb.OleDbCommand        cmd = new System.Data.OleDb.OleDbCommand(query, cn);
                System.Data.OleDb.OleDbDataAdapter    da  = new System.Data.OleDb.OleDbDataAdapter(cmd);
                System.Data.OleDb.OleDbCommandBuilder ocb = new System.Data.OleDb.OleDbCommandBuilder(da);
                //cn.Open();
                da.Fill(dt);
                ocb.QuoteSuffix = "]";
                ocb.QuotePrefix = "[";

                //  var insertBuilder = new StringBuilder();

                for (int i = 0; i < resultData.Rows.Count; i++)
                {
                    //DataRow dr = dt.NewRow();
                    //dr["Slno"] = dttemp.Rows[i][0];
                    //dr["RakeNo"] = txtRakeNo.Text;
                    //dr["WagonType"] = txtWagonType.Text;
                    dt.Rows[i]["WagonNo"] = resultData.Rows[i][1];
                    dt.Rows[i]["Tare"]    = resultData.Rows[i]["tare"];
                    dt.Rows[i]["Net"]     = resultData.Rows[i]["net"];
                    //dt.Rows[i]["datein"] = resultData.Rows[i]["datein"];
                    //dt.Rows[i]["timein"] = resultData.Rows[i]["timein"];
                    dt.Rows[i]["UL"]  = resultData.Rows[i]["UL"];
                    dt.Rows[i]["OL"]  = resultData.Rows[i]["OL"];
                    dt.Rows[i]["CC"]  = resultData.Rows[i]["CC"];
                    dt.Rows[i]["PCC"] = resultData.Rows[i]["PCC"];
                }
                da.Update(dt);

                MessageBox.Show("Successfully Updated");
                dgRakeView.DataSource = null;
                txtRakeNo.Clear();
                txtSlno.Clear();
            }
        }
        /// <summary>
        /// 查询通讯协议
        /// </summary>
        /// <param name="sql">查询语句</param>
        /// <param name="AccessPath">Access数据库路径</param>
        /// <param name="Ip">服务器数据库Ip地址</param>
        /// <param name="UserName">服务器登录名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        private DgnProtocolInfo GetProtocolInfo(string sql, string AccessPath, string Ip, string UserName, string pwd)
        {
            DgnProtocolInfo Items = new DgnProtocolInfo();
            bool            flag  = false;

            if (Ip != "")
            {
                flag = ConnectDataBase("", Ip, UserName, pwd);
            }
            else if (AccessPath != "")
            {
                flag = ConnectDataBase(AccessPath, "", "", "");
            }
            else
            {
                flag = ConnectDataBase("", "", "", "");
            }

            try
            {
                if (!flag)
                {
                    return(Items);
                }
                System.Data.OleDb.OleDbCommand    Cmd    = new System.Data.OleDb.OleDbCommand(sql, _Data.Con);
                System.Data.OleDb.OleDbDataReader Reader = Cmd.ExecuteReader();
                while (Reader.Read())
                {
                    Items.Pro_ProtocolID = Convert.ToInt32(Reader["ProtocolID"].ToString()); //协议编号
                    Items.Pro_proNameNo  = Convert.ToInt32(Reader["proNameNo"].ToString());  //通讯协议归属
                    Items.Pro_chrPname   = Reader["chrPname"].ToString();                    //协议名称
                    Items.Pro_intInfoNo  = Convert.ToInt32(Reader["intInfoNo"].ToString());  //信息序号
                    Items.Pro_chrValue   = Reader["chrValue"].ToString();                    //对应值
                }
                Reader.Close();
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message, "数据库操作错误", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            }
            finally
            {
                _Data.CloseDB();
            }
            return(Items);
        }
Beispiel #42
0
 public override DataTable GetSchemaTable(string sql)
 {
     try
     {
         using (var conn = new System.Data.OleDb.OleDbConnection(ProviderString))
         {
             conn.Open();
             var cmd = new System.Data.OleDb.OleDbCommand(sql, conn);
             var rdr = cmd.ExecuteReader(CommandBehavior.SchemaOnly);
             return(rdr.GetSchemaTable());
         }
     }
     catch
     {
         return(null);
     }
 }
 /// <summary>
 /// method when the submit solution button is clicked
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void button2_Click(object sender, EventArgs e)
 {
     System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\ASD\ase 2\user Database.accdb");
     connection.Open();                                           //opens connection
     if (codeID != null && src_class != null && solution != null) //if statement that makes sure certain fields are filled in
     {
         String query = "INSERT INTO fixed_code ([code ID], [user], [class], [method], [line], [solution], [time added]) VALUES(" + codeID.Text + ",'" + label3.Text + "','" + src_class.Text + "','" + method.Text + "'," + line.Text + ",'" + solution.Text + "','" + label4.Text + "')";
         //query that adds the values of the text boxes and rich text boxes to the database
         System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, connection);
         cmd.ExecuteNonQuery();                                           //executes query
         MessageBox.Show("Your solution has been added to the database"); // message box to confirm that the database has been updated
     }
     else
     {
         MessageBox.Show("Code id class and solution must be filled in");
     }
 }
Beispiel #44
0
        private DataSet GetMeSomeDataIntoDataSet(string sql)
        {
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
            conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Jason\Dropbox\Devry\CIS336\SimpleQueryAnalyzer\SimpleQueryAnalyzer\northwind.mdb;";
            conn.Open();
            System.Data.OleDb.OleDbCommand comm = new System.Data.OleDb.OleDbCommand();
            comm.Connection  = conn;
            comm.CommandText = sql;

            System.Data.DataSet ds = new DataSet();
            System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter();

            da.SelectCommand = comm;
            da.Fill(ds);

            return(ds);
        }
 /// <summary>
 /// Método necesario para admitir el Diseñador, no se puede modificar
 /// el contenido del método con el editor de código.
 /// </summary>
 private void InitializeComponent()
 {
     System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
     this.oleDbDataAdapter1   = new System.Data.OleDb.OleDbDataAdapter();
     this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
     this.oleDbConnection1    = new System.Data.OleDb.OleDbConnection();
     this.datosPagare1        = new envios_notaria_pagare.datosPagare();
     ((System.ComponentModel.ISupportInitialize)(this.datosPagare1)).BeginInit();
     //
     // oleDbDataAdapter1
     //
     this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1;
     this.oleDbDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
         new System.Data.Common.DataTableMapping("Table", "envioPagare", new System.Data.Common.DataColumnMapping[] {
             new System.Data.Common.DataColumnMapping("FOLIO", "FOLIO"),
             new System.Data.Common.DataColumnMapping("EMPRESA", "EMPRESA"),
             new System.Data.Common.DataColumnMapping("FECHA_EN", "FECHA_EN"),
             new System.Data.Common.DataColumnMapping("FECHA_ENVIO", "FECHA_ENVIO"),
             new System.Data.Common.DataColumnMapping("VALOR_PAGAR", "VALOR_PAGAR"),
             new System.Data.Common.DataColumnMapping("ESTADO_PAGARE", "ESTADO_PAGARE"),
             new System.Data.Common.DataColumnMapping("RUT_ALUMNO", "RUT_ALUMNO"),
             new System.Data.Common.DataColumnMapping("RUT_APODERADO", "RUT_APODERADO"),
             new System.Data.Common.DataColumnMapping("NOMBRE_APODERADO", "NOMBRE_APODERADO")
         })
     });
     //
     // oleDbSelectCommand1
     //
     this.oleDbSelectCommand1.CommandText = "SELECT \'\' AS FOLIO, \'\' AS EMPRESA, \'\' AS FECHA_EN, \'\' AS FECHA_ENVIO, \'\' AS VALOR" +
                                            "_PAGAR, \'\' AS ESTADO_PAGARE, \'\' AS RUT_ALUMNO, \'\' AS RUT_APODERADO, \'\' AS NOMBRE" +
                                            "_APODERADO, \'\' AS PAGA_NCORR FROM DUAL";
     this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
     //
     // oleDbConnection1
     //
     this.oleDbConnection1.ConnectionString = ((string)(configurationAppSettings.GetValue("cadenaConexion", typeof(string))));
     //
     // datosPagare1
     //
     this.datosPagare1.DataSetName = "datosPagare";
     this.datosPagare1.Locale      = new System.Globalization.CultureInfo("es-ES");
     this.datosPagare1.Namespace   = "http://www.tempuri.org/datosPagare.xsd";
     this.Load += new System.EventHandler(this.Page_Load);
     ((System.ComponentModel.ISupportInitialize)(this.datosPagare1)).EndInit();
 }
Beispiel #46
0
        /// <summary>
        /// xls文件转数据表
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static System.Data.DataTable XlsToData(string fileName)
        {
            string fileExtenSion;
            fileExtenSion = System.IO.Path.GetExtension(fileName);
            if (fileExtenSion.ToLower() != ".xls" && fileExtenSion.ToLower() != ".xlsx")
            {
                return null;
            }
            System.Data.OleDb.OleDbConnection conn = null;
            try
            {
                //HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES
                string connstr2003 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
                string connstr2007 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=YES\"";

                if (fileExtenSion.ToLower() == ".xls")
                {
                    conn = new System.Data.OleDb.OleDbConnection(connstr2003);
                }
                else
                {
                    conn = new System.Data.OleDb.OleDbConnection(connstr2007);
                }
                conn.Open();
                string sql = "select * from [Sheet1$]";
                System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, conn);
                System.Data.DataTable dt = new System.Data.DataTable();
                System.Data.OleDb.OleDbDataReader sdr = cmd.ExecuteReader();

                dt.Load(sdr);
                sdr.Close();
                conn.Close();

                return dt;
            }
            catch
            {
                return null;
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }
Beispiel #47
0
 /// <summary>
 /// Método necesario para admitir el Diseñador, no se puede modificar
 /// el contenido del método con el editor de código.
 /// </summary>
 private void InitializeComponent()
 {
     System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
     this.oleDbDataAdapter1   = new System.Data.OleDb.OleDbDataAdapter();
     this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
     this.oleDbConnection1    = new System.Data.OleDb.OleDbConnection();
     this.datosAlumno1        = new ficha_alumno.datosAlumno();
     ((System.ComponentModel.ISupportInitialize)(this.datosAlumno1)).BeginInit();
     //
     // oleDbDataAdapter1
     //
     this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1;
     this.oleDbDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
         new System.Data.Common.DataTableMapping("Table", "alumno", new System.Data.Common.DataColumnMapping[] {
             new System.Data.Common.DataColumnMapping("ANO_INGRESO", "ANO_INGRESO"),
             new System.Data.Common.DataColumnMapping("NOMBRE_SEDE", "NOMBRE_SEDE"),
             new System.Data.Common.DataColumnMapping("NOMBRE_ALUMNO", "NOMBRE_ALUMNO"),
             new System.Data.Common.DataColumnMapping("RUT_POST", "RUT_POST"),
             new System.Data.Common.DataColumnMapping("CARRERA", "CARRERA"),
             new System.Data.Common.DataColumnMapping("DIRECCION", "DIRECCION"),
             new System.Data.Common.DataColumnMapping("FONO", "FONO"),
             new System.Data.Common.DataColumnMapping("CIUDAD", "CIUDAD"),
             new System.Data.Common.DataColumnMapping("COMUNA", "COMUNA")
         })
     });
     //
     // oleDbSelectCommand1
     //
     this.oleDbSelectCommand1.CommandText = "SELECT \'\' AS ANO_INGRESO, \'\' AS NOMBRE_SEDE, \'\' AS NOMBRE_ALUMNO, \'\' AS RUT_POST," +
                                            " \'\' AS CARRERA, \'\' AS DIRECCION, \'\' AS FONO, \'\' AS CIUDAD, \'\' AS COMUNA FROM DUA" +
                                            "L";
     this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
     //
     // oleDbConnection1
     //
     this.oleDbConnection1.ConnectionString = ((string)(configurationAppSettings.GetValue("cadenaConexion", typeof(string))));
     //
     // datosAlumno1
     //
     this.datosAlumno1.DataSetName = "datosAlumno";
     this.datosAlumno1.Locale      = new System.Globalization.CultureInfo("es-ES");
     this.datosAlumno1.Namespace   = "http://www.tempuri.org/datosAlumno.xsd";
     this.Load += new System.EventHandler(this.Page_Load);
     ((System.ComponentModel.ISupportInitialize)(this.datosAlumno1)).EndInit();
 }
Beispiel #48
0
 public void UpdateByProcedure(string procedureName, System.Data.OleDb.OleDbParameter[] sqlParameter)
 {
     try
     {
         System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(procedureName, managerDB.OpenApp());
               command.CommandType = System.Data.CommandType.StoredProcedure;
         for (int i = 0; i < sqlParameter.Length; i++)
         {
             command.Parameters.Add(sqlParameter[i]);
         }
         command.ExecuteNonQuery();
     }
     catch (Exception exception)
     {
         IAppLog log = (IAppLog)AppLogFactory.LogProduct();
         log.writeLog(this.GetType().Name, "执行存储过程出错!" + exception.ToString());
     }
 }
Beispiel #49
0
 internal static System.Data.DataSet getXldata(System.Data.OleDb.OleDbConnection xlConn, string sheetName, string excelPath, string excelExten)
 {
     System.Data.DataSet ds = new System.Data.DataSet();
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
         xlConn     = new global::System.Data.OleDb.OleDbConnection(Utilities.ConnUtilities.CreateXlConnectionString(excelPath, excelExten));
         string cmd = string.Format("select * from [{0}]", sheetName);
         System.Data.OleDb.OleDbCommand Comm = new System.Data.OleDb.OleDbCommand(cmd, xlConn);
         Comm.Connection = xlConn;
         System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
         xlConn.Open();
         Comm.CommandType      = System.Data.CommandType.Text;
         adapter.SelectCommand = Comm;
         adapter.Fill(ds);
         xlConn.Close();
     });
     return(ds);
 }
Beispiel #50
0
 public System.Data.DataTable get_data_from_excell()
 {
     System.Data.DataTable bang = new System.Data.DataTable();
     try
     {
         con = new System.Data.OleDb.OleDbConnection(sConnectionString);
         con.Open();
         System.Data.OleDb.OleDbCommand     lenh      = new System.Data.OleDb.OleDbCommand("SELECT * FROM [Sheet1$]", con);
         System.Data.OleDb.OleDbDataAdapter thich_ung = new System.Data.OleDb.OleDbDataAdapter();
         thich_ung.SelectCommand = lenh;
         thich_ung.Fill(bang);
         con.Close();
     }
     catch
     {
     }
     return(bang);
 }
Beispiel #51
0
        public int ModifyDatabase(string queryString)
        {
            configureConnection();
            using (conn){
                System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(queryString);
                command.Connection = conn;

                try{
                    conn.Open();
                    command.ExecuteNonQuery();
                    return(0);
                }
                catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                    return(1);
                }
            }
        }
Beispiel #52
0
        public static System.Data.OleDb.OleDbDataReader GetWDSResults(IList <WDSField> fields, string scope, string extention, System.Data.OleDb.OleDbConnection wds_connection)
        {
            var fieldnames = System.String.Join(",", fields.Select(f => f.Name));

            var sb = new System.Text.StringBuilder();

            sb.AppendFormat(@"SELECT {0} ", fieldnames);
            sb.AppendFormat(@"FROM SYSTEMINDEX  ");

            var clauses = new List <string>();

            if (scope != null)
            {
                clauses.Add(string.Format(@"SCOPE='{0}' ", scope));
            }
            if (extention != null)
            {
                clauses.Add(string.Format(@"System.ItemType='{0}' ", extention));
            }

            if (clauses.Count > 0)
            {
                sb.AppendFormat(@"WHERE ");

                int n = 0;
                foreach (string clause in clauses)
                {
                    if (n > 0)
                    {
                        sb.Append(" AND ");
                    }
                    sb.Append(clause);
                    n++;
                }
            }

            string wds_query = sb.ToString();

            var x = System.String.Format(
                @"SELECT {0} FROM SYSTEMINDEX WHERE SCOPE='{1}' AND System.ItemType = '.mp3'", fieldnames, scope);
            var wds_command = new System.Data.OleDb.OleDbCommand(wds_query, wds_connection);

            return(wds_command.ExecuteReader());
        }
Beispiel #53
0
        private void btnGo_Click(object sender, EventArgs e)
        {
            lblError.Text = "";
            //open connection to database

            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
            conn.ConnectionString = txtConnString.Text;
            conn.Open();
            // MessageBox.Show(conn.State.ToString());
            //create my command
            System.Data.OleDb.OleDbCommand comm = new System.Data.OleDb.OleDbCommand();
            comm.Connection = conn;
            //send the sql through the command
            comm.CommandText = txtSQL.Text;

            //receive the result into a data container.

            System.Data.OleDb.OleDbDataReader dr;
            try
            {
                if (txtSQL.Text.ToUpper().StartsWith("SELECT"))
                {
                    dr = comm.ExecuteReader();
                    System.Data.DataTable dt = new DataTable();
                    dt.Load(dr);
                    Grid1.AutoGenerateColumns = true;
                    //bind the result to the grid

                    Grid1.DataSource = dt;
                }
                else
                {
                    MessageBox.Show(comm.ExecuteNonQuery().ToString());
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
            finally
            {
                conn.Close();
            }
        }
 /// <summary>
 /// Método necesario para admitir el Diseñador, no se puede modificar
 /// el contenido del método con el editor de código.
 /// </summary>
 private void InitializeComponent()
 {
     System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
     this.oleDbDataAdapter1   = new System.Data.OleDb.OleDbDataAdapter();
     this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
     this.oleDbConnection1    = new System.Data.OleDb.OleDbConnection();
     this.datos1 = new Pres_Ingreso_Real.Datos();
     ((System.ComponentModel.ISupportInitialize)(this.datos1)).BeginInit();
     //
     // oleDbDataAdapter1
     //
     this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1;
     this.oleDbDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
         new System.Data.Common.DataTableMapping("Table", "ProsupuestadoReal", new System.Data.Common.DataColumnMapping[] {
             new System.Data.Common.DataColumnMapping("CARR_TDESC", "CARR_TDESC"),
             new System.Data.Common.DataColumnMapping("CARR_CCOD", "CARR_CCOD"),
             new System.Data.Common.DataColumnMapping("TOTAL_MATR_COMPROMETIDA", "TOTAL_MATR_COMPROMETIDA"),
             new System.Data.Common.DataColumnMapping("TOTAL_COL_COMPROMETIDA", "TOTAL_COL_COMPROMETIDA"),
             new System.Data.Common.DataColumnMapping("TOTAL_MATR_REAL", "TOTAL_MATR_REAL"),
             new System.Data.Common.DataColumnMapping("TOTAL_COL_REAL", "TOTAL_COL_REAL"),
             new System.Data.Common.DataColumnMapping("SALDO", "SALDO")
         })
     });
     //
     // oleDbSelectCommand1
     //
     this.oleDbSelectCommand1.CommandText = "SELECT \'\' AS SEDE_TDESC, \'\' AS CARR_TDESC, \'\' AS CARR_CCOD, \'\' AS TOTAL_MATR_COMP" +
                                            "ROMETIDA, \'\' AS TOTAL_COL_COMPROMETIDA, \'\' AS TOTAL_MATR_REAL, \'\' AS TOTAL_COL_R" +
                                            "EAL, \'\' AS SALDO, \'\' AS PERIODO, \'\' AS FECHA_INICIO, \'\' AS FECHA_TERMINO FROM DU" +
                                            "AL";
     this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
     //
     // oleDbConnection1
     //
     this.oleDbConnection1.ConnectionString = ((string)(configurationAppSettings.GetValue("cadenaConexion", typeof(string))));
     //
     // datos1
     //
     this.datos1.DataSetName = "Datos";
     this.datos1.Locale      = new System.Globalization.CultureInfo("es-ES");
     this.datos1.Namespace   = "http://www.tempuri.org/Datos.xsd";
     this.Load += new System.EventHandler(this.Page_Load);
     ((System.ComponentModel.ISupportInitialize)(this.datos1)).EndInit();
 }
Beispiel #55
0
 /// <summary>
 /// Método necesario para admitir el Diseñador, no se puede modificar
 /// el contenido del método con el editor de código.
 /// </summary>
 private void InitializeComponent()
 {
     System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
     this.oleDbDataAdapter1   = new System.Data.OleDb.OleDbDataAdapter();
     this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
     this.oleDbConnection1    = new System.Data.OleDb.OleDbConnection();
     this.datosReporte1       = new rep_det_cob.datosReporte();
     ((System.ComponentModel.ISupportInitialize)(this.datosReporte1)).BeginInit();
     //
     // oleDbDataAdapter1
     //
     this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1;
     this.oleDbDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
         new System.Data.Common.DataTableMapping("Table", "reporte", new System.Data.Common.DataColumnMapping[] {
             new System.Data.Common.DataColumnMapping("TIPO", "TIPO"),
             new System.Data.Common.DataColumnMapping("FECHA_EMISION", "FECHA_EMISION"),
             new System.Data.Common.DataColumnMapping("NRO_NDOCTO", "NRO_NDOCTO"),
             new System.Data.Common.DataColumnMapping("MONTO", "MONTO"),
             new System.Data.Common.DataColumnMapping("FECHA_VEN", "FECHA_VEN"),
             new System.Data.Common.DataColumnMapping("ESTADO", "ESTADO"),
             new System.Data.Common.DataColumnMapping("RUT_ALUMNO", "RUT_ALUMNO"),
             new System.Data.Common.DataColumnMapping("RUT_APODERADO", "RUT_APODERADO")
         })
     });
     //
     // oleDbSelectCommand1
     //
     this.oleDbSelectCommand1.CommandText = "SELECT \'\' AS TIPO, \'\' AS FECHA_EMISION, \'\' AS NRO_NDOCTO, \'\' AS MONTO, \'\' AS FECH" +
                                            "A_VEN, \'\' AS ESTADO, \'\' AS RUT_ALUMNO, \'\' AS RUT_APODERADO, \'\' AS C_CORRIENTE FR" +
                                            "OM DUAL";
     this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
     //
     // oleDbConnection1
     //
     this.oleDbConnection1.ConnectionString = ((string)(configurationAppSettings.GetValue("cadenaConexion", typeof(string))));
     //
     // datosReporte1
     //
     this.datosReporte1.DataSetName = "datosReporte";
     this.datosReporte1.Locale      = new System.Globalization.CultureInfo("es-ES");
     this.datosReporte1.Namespace   = "http://www.tempuri.org/datosReporte.xsd";
     this.Load += new System.EventHandler(this.Page_Load);
     ((System.ComponentModel.ISupportInitialize)(this.datosReporte1)).EndInit();
 }
Beispiel #56
0
 /// <summary>
 /// Método necesario para admitir el Diseñador, no se puede modificar
 /// el contenido del método con el editor de código.
 /// </summary>
 private void InitializeComponent()
 {
     System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
     this.DbConnection        = new System.Data.OleDb.OleDbConnection();
     this.DbDataAdapter       = new System.Data.OleDb.OleDbDataAdapter();
     this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
     this.dataSetMorosidad1   = new MorosidadFinanzas.DataSetMorosidad();
     ((System.ComponentModel.ISupportInitialize)(this.dataSetMorosidad1)).BeginInit();
     //
     // DbConnection
     //
     this.DbConnection.ConnectionString = ((string)(configurationAppSettings.GetValue("cadenaConexion", typeof(string))));
     //
     // DbDataAdapter
     //
     this.DbDataAdapter.SelectCommand = this.oleDbSelectCommand1;
     this.DbDataAdapter.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
         new System.Data.Common.DataTableMapping("Table", "T_Morosidad", new System.Data.Common.DataColumnMapping[] {
             new System.Data.Common.DataColumnMapping("FECHA_CORTE", "FECHA_CORTE"),
             new System.Data.Common.DataColumnMapping("SEDE_TDESC", "SEDE_TDESC"),
             new System.Data.Common.DataColumnMapping("CARRERA", "CARRERA"),
             new System.Data.Common.DataColumnMapping("RUT", "RUT"),
             new System.Data.Common.DataColumnMapping("NOMBRE", "NOMBRE"),
             new System.Data.Common.DataColumnMapping("COMPROMETIDO", "COMPROMETIDO"),
             new System.Data.Common.DataColumnMapping("LETRAS", "LETRAS"),
             new System.Data.Common.DataColumnMapping("CHEQUES", "CHEQUES"),
             new System.Data.Common.DataColumnMapping("PAGARE", "PAGARE")
         })
     });
     //
     // oleDbSelectCommand1
     //
     this.oleDbSelectCommand1.CommandText = "SELECT \'\' AS FECHA_CORTE, \'\' AS SEDE_TDESC, \'\' AS CARRERA, \'\' AS RUT, \'\' AS NOMBR" +
                                            "E, \'\' AS COMPROMETIDO, \'\' AS LETRAS, \'\' AS CHEQUES, \'\' AS PAGARE FROM DUAL";
     this.oleDbSelectCommand1.Connection = this.DbConnection;
     //
     // dataSetMorosidad1
     //
     this.dataSetMorosidad1.DataSetName = "DataSetMorosidad";
     this.dataSetMorosidad1.Locale      = new System.Globalization.CultureInfo("es-CL");
     this.dataSetMorosidad1.Namespace   = "http://www.tempuri.org/DataSetMorosidad.xsd";
     this.Load += new System.EventHandler(this.Page_Load);
     ((System.ComponentModel.ISupportInitialize)(this.dataSetMorosidad1)).EndInit();
 }
        public DataSet updtedata(string sortfield)
        {
            System.Data.OleDb.OleDbConnection conn = GetConnection();
            DataSet ds = new DataSet();

            try
            {
                string sqlupdate = default(string);

                sqlupdate = "UPDATE Table1 set STUDENTID=@STUDENTID, data1=@data1, data2=@data2, data3=@data3, data4=@data4," + "data5=@data5, data6=@data6, data7=@data7, data8=@data8, data9=@data9, data10=@data10," + "data11=@data11, data12=@data12, data13=@data13, data14=@data14, data15=@data15, data16=@data16," + "data17=@data17, data18=@data18, data19=@data19 where STUDENTID=\'" + Form1.Default.STUDID.Text + "\'";
                System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sqlupdate, conn);

                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@STUDENTID", Form1.Default.STUDID.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA1", Form1.Default.TextBox1.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA2", Form1.Default.TextBox2.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA3", Form1.Default.TextBox3.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA4", Form1.Default.TextBox4.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA5", Form1.Default.TextBox5.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA6", Form1.Default.TextBox6.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA7", Form1.Default.TextBox7.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA8", Form1.Default.TextBox8.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA9", Form1.Default.TextBox9.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA10", Form1.Default.TextBox10.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA11", Form1.Default.TextBox11.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA12", Form1.Default.TextBox12.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA13", Form1.Default.TextBox13.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA14", Form1.Default.TextBox14.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA15", Form1.Default.TextBox15.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA16", Form1.Default.TextBox16.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA17", Form1.Default.TextBox17.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA18", Form1.Default.TextBox18.Text));
                cmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("@DATA19", Form1.Default.TextBox19.Text));

                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
                MessageBox.Show("Data Updated in the Database");
                RefreshDGV();
            }
            finally
            {
            }
            return(ds);
        }
Beispiel #58
0
        // Return the adjective's exception singular to plurial group
        public static string groupS2POf(string adjective, string gender, string number)
        {
            string res = "";

            // we transform the adjective to male singular if it is not
            if (number == "P")
            {
                adjective = plurialToSingular(adjective);
            }
            if (gender == "F")
            {
                adjective = femaleToMale(adjective);
            }
            // if the IA knows the adjective, we only have to make a research on the data base
            if (existe(adjective))
            {
                con.Open();
                res = new CMD("SELECT GroupS2P FROM Adjectifs WHERE Adjective = '" + adjective + "'", con).ExecuteScalar().ToString();
                con.Close();
            }
            // else, we had to estimate it
            else
            {
                int    length = adjective.Length;
                string ending = "";
                object resEnding;
                con.Open();
                for (int i = length; res == "" && i >= 1; i--)
                {
                    ending    = adjective.Substring(length - i);
                    resEnding = new CMD("SELECT GroupS2P FROM ExceptionsAdjectifsS2P WHERE Singular = '" + ending + "' ORDER BY GroupS2P ", con).ExecuteScalar();
                    if (resEnding != null)
                    {
                        res = resEnding.ToString();
                    }
                }
            }
            con.Close();
            if (res == "")
            {
                res = "10";
            }
            return(res);
        }
Beispiel #59
0
        private void save(Report r, System.Data.OleDb.OleDbConnection con)
        {
            string      cmd;
            TextManager mng = new TextManager();

            string[] text = new string[r.Items.Count];
            cmd  = "Insert into Diagn (FIO, Dat, Name) Values (";
            cmd += "\"" + r.FIO + "\", ";
            cmd += "\"" + r.Date.ToShortDateString() + "\", ";
            cmd += "\"" + (string)r.Tag + "\");";
            con.Open();
            System.Data.OleDb.OleDbCommand c =
                new System.Data.OleDb.OleDbCommand(cmd, con);
            c.ExecuteNonQuery();
            cmd = "Select max(ID) From Diagn;";
            c   = new System.Data.OleDb.OleDbCommand(cmd, con);
            mng.Save(r, c.ExecuteScalar());
            con.Close();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Mostrar na listBox2 os alunos do curso selecionado no listBox1:
            try
            {
                listBox2.Items.Clear(); //limpamos a segunda lista
                string cursoSelec = (string)((DataRowView)listBox1.SelectedItem)[0];

                string sql = "SELECT * FROM Alunos WHERE abrevcurso = '" + cursoSelec + "'";

                //suponhamos o BD em C:\tempo
                System.Data.OleDb.OleDbConnection conexao =
                    new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/temp/Universidade3.mdb");
                conexao.Open();

                System.Data.OleDb.OleDbCommand comando =
                    new System.Data.OleDb.OleDbCommand(sql, conexao);

                System.Data.OleDb.OleDbDataReader dr = comando.ExecuteReader();

                while (dr.Read())
                {
                    string dadosAluno = dr.GetString(0)
                        + ", " + dr.GetString(1) + ", " + dr.GetString(2)
                        + ", " + dr.GetInt32(3) + ", " + dr.GetString(4);
                    listBox2.Items.Add(dadosAluno);
                }

                dr.Close();
                comando.Dispose();
                conexao.Close();
            }
            catch (Exception exc) { MessageBox.Show(exc.Message); }
        }