当前位置: 首页>>代码示例>>C#>>正文


C# Odbc.OdbcConnection类代码示例

本文整理汇总了C#中System.Data.Odbc.OdbcConnection的典型用法代码示例。如果您正苦于以下问题:C# OdbcConnection类的具体用法?C# OdbcConnection怎么用?C# OdbcConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


OdbcConnection类属于System.Data.Odbc命名空间,在下文中一共展示了OdbcConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: BuscaDados

        /// <summary>
        /// Executa uma query de busca com retorno de dados
        /// </summary>
        /// <param name="sql">comando sql para aquela ação</param>
        /// <returns>Um dataset contendo os dados buscados</returns>
        public DataSet BuscaDados(string sql)
        {   
            //Instancia um objeto de dataset para retornar
            DataSet dados = new DataSet();

            using(OdbcConnection conn = new OdbcConnection(this.ConnectionString))
            {
                try
                {               
                    //Abre a conexão com o servidor de banco
                    conn.Open();
                    //Cria um objeto de reader do odbc, para retornar dados
                    OdbcDataAdapter read = new OdbcDataAdapter(sql, conn);

                    //Preenche o DataSet instanciado no incio do codigo
                    read.Fill(dados);
                }
                catch (Exception ex)
                {
                    //Lança um erro, caso aconteça
                    throw new Exception(ex.Message);
                }
                finally
                {
                    //Fecha conexão
                    conn.Close();
                }
            }

            return dados;
        }
开发者ID:dielduarte,项目名称:votaai,代码行数:36,代码来源:Conexao.cs

示例2: setClientDBData

        public void setClientDBData(string clientId)
        {
            try
            {
                #region get values from DB and set the clients prop
                string cmd = "SELECT smoker_code, smoker_value, smoking_stat_assess_date, ss_demographics_dict_8_code,ss_demographics_dict_8_value " +
                                "FROM patient_current_demographics " +
                                "WHERE PATID = ?";
                using (OdbcConnection con = new OdbcConnection(ConnectionStringPM))
                {
                    con.Open();
                    using (var command = new OdbcCommand(cmd, con))
                    {
                        command.Parameters.Add(new OdbcParameter("PATID", clientId));

                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                this.client.Id = clientId;
                                this.client.LGBT = reader["ss_demographics_dict_8_code"].ToString();
                                this.client.SmokerStatus = reader["smoker_code"].ToString();
                            }
                        }
                    }
                }
                status = "ClientId = " + clientId + "<br>" +
                         "LGBT = " + this.client.LGBT + "<br>" +
                         "Smoker = " + this.client.SmokerStatus + "<br>";
                #endregion
            }
            catch (Exception exc) { status = exc.ToString(); }
        }
开发者ID:yoismelp,项目名称:TestScriptLink2YP,代码行数:33,代码来源:ClientDBData.cs

示例3: SetupSqlServerOdbc

		private static void SetupSqlServerOdbc(Cfg.Configuration cfg)
		{
			var connStr = cfg.Properties[Cfg.Environment.ConnectionString];

			using (var conn = new OdbcConnection(connStr.Replace("Database=nhibernateOdbc", "Database=master")))
			{
				conn.Open();

				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = "drop database nhibernateOdbc";

					try
					{
						cmd.ExecuteNonQuery();
					}
					catch(Exception e)
					{
						Console.WriteLine(e);
					}

					cmd.CommandText = "create database nhibernateOdbc";
					cmd.ExecuteNonQuery();
				}
			}
		}
开发者ID:marchlud,项目名称:nhibernate-core,代码行数:26,代码来源:TestDatabaseSetup.cs

示例4: MyConnectionOdbc

        public MyConnectionOdbc(DataProvider dataProvider)
            : base(dataProvider)
        {
            // Crear conexión
            OdbcConnection conn = new OdbcConnection(@"provider = sqlodbc;
                data source = .\sqlexpress; trusted connection = yes;");

            try
            {
                // Abrir conexión
                conn.Open();
                Console.WriteLine("Conexión establecida.");

                // Detalles de la conexión
                this.DetallesConexion(conn);
            }
            catch (OdbcException ex)
            {
                // Desplegar excepción o error
                Console.WriteLine("Error: " + ex.Message + ex.StackTrace);
            }
            finally
            {
                //Cerrar la conexión
                conn.Close();
            }
        }
开发者ID:POO-III-2015,项目名称:FabricaConexiones,代码行数:27,代码来源:MyConnectionOdbc.cs

示例5: getImagen

    /// <summary>
    /// retorna una imagen
    /// </summary>
    /// <returns></returns>
    public static Imagen getImagen(OdbcConnection con, int idImagen)
    {
        DataSet ds = new DataSet();
        Imagen imagen = new Imagen();
        try
        {
            OdbcCommand cmd = new OdbcCommand("SELECT i.id, i.pathBig, i.pathSmall, i.portada, i.pathMedium FROM imagen i WHERE i.id=" + idImagen, con);
            cmd.CommandType = CommandType.Text;
            OdbcDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                imagen.IdImagen = dr.GetInt32(0);
                imagen.PathBig = dr.GetString(1);
                imagen.PathSmall = dr.GetString(2);
                imagen.Portada = dr.GetBoolean(3);
                imagen.PathMedium = dr.GetString(4);
            }
        }
        catch (Exception e)
        {
            throw new SportingException("Ocurrio un problema al intentar obtener la imagen. " + e.Message);
        }
        return imagen;
    }
开发者ID:branux,项目名称:sporting-pag-web,代码行数:29,代码来源:ImagenDAL.cs

示例6: GetAccountExists

        // Check esistenza account
        public bool GetAccountExists(String username, out String error)
        {
            bool exists = false;
            error = "";

            try
            {
                // Connesione db
                OdbcConnection odbc = new OdbcConnection("DSN=nwn_master_server");
                odbc.Open();

                using (OdbcCommand dbcmd = odbc.CreateCommand()) {
                    // Query
                    String query = "SELECT username FROM " + TABLE_ACCOUNTS + " WHERE username='" + username + "'";
                    dbcmd.CommandText = query;

                    using (OdbcDataReader dbreader = dbcmd.ExecuteReader()) {
                        while(dbreader.Read()){
                            if ((String)dbreader["username"] == username)
                                exists = true;
                        }

                        dbreader.Close();
                    }
                }

                odbc.Close();
            }
            catch (Exception e) {
                error = e.StackTrace;
            }

            // Exit
            return exists;
        }
开发者ID:SpiderMurphy,项目名称:nwn-tricks,代码行数:36,代码来源:Sql.cs

示例7: GetOpenConnection

        public static DbConnection GetOpenConnection(AdoProviderType providerType, string connStr, int retryCount, int retryDelay)
        {
            DbConnection conn = null;
            switch (providerType)
            {
                case AdoProviderType.SqlProvider:
                    conn = new SqlConnection(connStr);
                    break;
                case AdoProviderType.OleProvider:
                    conn = new OleDbConnection(connStr);
                    break;
                case AdoProviderType.OdbcProvider:
                    conn = new OdbcConnection(connStr);
                    break;
                default:
                    throw new Exception("This provider type is not supported.");
            }


            if (conn != null)
            {
                conn.Open();
                int attemptCount = 0;
                while (conn.State!=ConnectionState.Open && ++attemptCount < retryCount)
                {
                    System.Threading.Thread.Sleep(retryDelay);
                    conn.Open();
                }
                if (conn.State != ConnectionState.Open)
                    throw new Exception("Unable to open connection using specified connection string.");
            }
            return conn;
        }
开发者ID:tenshino,项目名称:RainstormStudios,代码行数:33,代码来源:rsData.cs

示例8: addUser

        private String addUser()
        {
            try
            {
                Contract contract = new Contract();
                String cxnString = "Driver={SQL Server};Server=HC-sql7;Database=REVINT;Trusted_Connection=yes;";
                using (OdbcConnection dbConnection = new OdbcConnection(cxnString))
                {
                    //open OdbcConnection object
                    dbConnection.Open();

                    OdbcCommand cmd = new OdbcCommand();

                    cmd.CommandText = "{CALL [REVINT]." + contract.getSchema() + ".[OCP_addUser]( ?, ?, ?, ? )}";
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Connection = dbConnection;

                    cmd.Parameters.Add("@hawkId", OdbcType.NVarChar, 400).Value = txtHealthcareID.Text;
                    cmd.Parameters.Add("@administrator", OdbcType.Bit).Value = chkAdmin.IsChecked;
                    cmd.Parameters.Add("@name", OdbcType.NVarChar, 400).Value = txtName.Text;
                    cmd.Parameters.Add("@numRecords", OdbcType.Int);
                    cmd.Parameters["@numRecords"].Direction = System.Data.ParameterDirection.ReturnValue;

                    cmd.ExecuteNonQuery();

                    dbConnection.Close();

                    return cmd.Parameters["@numRecords"].Value.ToString();
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
开发者ID:ep2012,项目名称:OCP-2.0,代码行数:35,代码来源:AddUser.xaml.cs

示例9: Button1_Click

    protected void Button1_Click(object sender, EventArgs e)
    {
        string[] strArray = new string[5] { "Delhi", "Mumbai", "Kolkata", "Chennai", "Chandigarh" };
        foreach (string str in strArray)
        {
           OdbcConnection oledbConn = new OdbcConnection("DSN=exceldb");
        try
        {
            // Open connection
            oledbConn.Open();

            // Create OleDbCommand object and select data from worksheet Sheet1
            OdbcCommand cmd = new OdbcCommand("SELECT * FROM [Details$]", oledbConn);
            //cmd.Parameters.AddWithValue("@city",str);where [email protected]
            // Create new OleDbDataAdapter
            OdbcDataAdapter oleda = new OdbcDataAdapter();

            oleda.SelectCommand = cmd;

            // Create a DataSet which will hold the data extracted from the worksheet.
            // DataSet ds = new DataSet();
            DataTable dt = new DataTable();

            // Fill the DataSet from the data extracted from the worksheet.
            oleda.Fill(dt);
            /*      if(dt.Rows.Count>0)
                  {
                       ID = dt.Rows[0]["ID"].ToString(); //Where ColumnName is the Field from the DB that you want to display
                       name= dt.Rows[0]["Name"].ToString();
                       Address = dt.Rows[0]["Address"].ToString();
                       EmailAddress = dt.Rows[0]["emailaddress"].ToString();
                       if(EmailAddress!=null)
                       {
                        if(EmailAddress==)
                       }
                       EmailContent = dt.Rows[0]["emailcontent"].ToString();
                   }
              */
            DataView dv = new DataView(dt);
            // dv.Sort = "emailcontents";
            // dv.Sort = "Name";

            // Bind the data to the GridView
            Grdexcel.DataSource = dv;
            Grdexcel.DataBind();
            // cmd = new OdbcCommand("delete FROM [ter$] where Address like 'M%'", oledbConn);
            // cmd.ExecuteNonQuery();
            //cmd.CommandType
        }
        catch (Exception ex)
        {
            Alert.Show("Sorry");
        }
        finally
        {
            // Close connection
            oledbConn.Close();
        }
        }
    }
开发者ID:nitishpandey,项目名称:semiprecious,代码行数:60,代码来源:excelsheet.aspx.cs

示例10: button1_Click

        /* queries for all students (IDs, First names, last names)
         * whose ID numbers contain the values provided by the student W# field
         * in the current form. */
        private void button1_Click(object sender, System.EventArgs e)
        {
            //Refresh the listview.
            searchView.Items.Clear();
            string SearchTerm = searchField.Text;
            System.Data.Odbc.OdbcConnection connection = new System.Data.Odbc.OdbcConnection(dsnSource);

            try
            {
                connection.Open();
                System.Data.Odbc.OdbcCommand command = connection.CreateCommand();
                command.CommandText = "SELECT ID, FIRST_NAME, LAST_NAME FROM G_PERSON WHERE ID like '%" + SearchTerm + "%'";
                System.Data.Odbc.OdbcDataReader Reader = command.ExecuteReader();
                while (Reader.Read())
                {
                    String id = Reader["ID"].ToString();
                    String fname = Reader["FIRST_NAME"].ToString();
                    String lname = Reader["LAST_NAME"].ToString();
                    ListViewItem item = new ListViewItem(new[] { id, fname, lname });
                    searchView.Items.Add(item);

                }
                connection.Close();
            } catch (Exception s) {
                MessageBox.Show("Could not connect at this time. Please try again later.");
                MessageBox.Show(s.ToString());
            }
        }
开发者ID:CodeKodama,项目名称:MajorEvaluationApplication,代码行数:31,代码来源:SearchWindow.cs

示例11: AddTermCode

    public bool AddTermCode(TermCode termCode)
    {
        bool result = false;

        using (OdbcConnection connection = new OdbcConnection(connectionString))
        {
            using (OdbcCommand command = new OdbcCommand())
            {
                command.Connection = connection;
                command.CommandText = "{CALL TermCode_insert(?,?)}";
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.AddWithValue("@AssessmentOID", termCode.AssessmentOID);
                command.Parameters.AddWithValue("@TermCodeName", termCode.TermCodeName);
                connection.Open();
                int n = command.ExecuteNonQuery();
                if (n > 0)
                    result = true;
                else
                    result = false;
            }
        }

        return result;
    }
开发者ID:mominbd,项目名称:testing,代码行数:25,代码来源:TermCode.cs

示例12: Button1_Click1

    protected void Button1_Click1(object sender, EventArgs e)
    {
        int i;
        string htmlstr = "<table style='width:100%;'>";
        string data;
        string sql = TextBox1.Text;
        string constr = Session["connection"].ToString();
        OdbcConnection cn = new OdbcConnection(constr);
        cn.Open();
        OdbcCommand cmd = new OdbcCommand(sql, cn);
        OdbcDataReader reader;
        reader = cmd.ExecuteReader();
        int col_count = reader.FieldCount;
        int count1;

        while (reader.Read())
        {
            htmlstr += "<tr>";
            count1 = col_count;
            i = 0;
            while (count1 != 0)
            {
                data = reader[i].ToString();
                htmlstr += "<td class='style2'>" + data + "</td>";
                count1--;
                i++;
            }
            htmlstr += "</tr>";
        }
        htmlstr += "</table>";
        table_data.InnerHtml = htmlstr;
    }
开发者ID:ashishvshenoy,项目名称:Insurance-DBMS-2,代码行数:32,代码来源:ReportPage.aspx.cs

示例13: Load_Sport_TXT_TO_DB_ByTableNameAndFieldName

 public static void Load_Sport_TXT_TO_DB_ByTableNameAndFieldName(string table_name, string field_names)
 {
     OpenFileDialog ofd = new OpenFileDialog();
     if (ofd.ShowDialog() == DialogResult.OK)
     {
         using (OdbcConnection conn = new OdbcConnection(Basic_HTB_Info.Conn_Str))
         {
             conn.Open();
             //MessageBox.Show(String.Format("TRUNCATE TABLE {0};", table_name));
             //using (OdbcCommand cmd = new OdbcCommand(String.Format("TRUNCATE TABLE {0};", table_name), conn))
             //{
              //   cmd.ExecuteNonQuery();
             //}
             StreamReader sr = new StreamReader(ofd.FileName,Encoding.Default);
             string line = null;
             while ((line = sr.ReadLine()) != null)
             {
                 string[] str_a = line.Split(';');
                 String[] fieldnames = field_names.Split(',');
                 if (str_a.Length == fieldnames.Length)
                 {
                     Lib.inc_cmd(field_names, table_name, str_a, conn);
                 }
             }
             conn.Close();
         }
     }
 }
开发者ID:eddylin2015,项目名称:sportday,代码行数:28,代码来源:Lib.cs

示例14: ExecuteQuery

        public static DataTable ExecuteQuery(string dsnConnection, string query, params object[] queryParams)
        {
            try
            {
                using (var connection = new OdbcConnection(dsnConnection))
                {
                    connection.Open();
                    var queryCommand = connection.CreateCommand();
                    queryCommand.CommandText = query;
                    queryCommand.CommandTimeout = 1;

                    var i = 0;
                    foreach (var queryParam in queryParams)
                    {
                        queryCommand.Parameters.Add("@p" + i, OdbcType.DateTime).Value = queryParam;
                        i++;
                    }

                    var dataSet = new DataSet();
                    var da = new OdbcDataAdapter(queryCommand);
                    da.Fill(dataSet);
                    return dataSet.Tables[0];
                }
            } catch(Exception ex)
            {
                Logging.LogError(1, "Error executing query {0} on connection {1} message is {2}", query, dsnConnection, ex.Message);
                throw;
            }
        }
开发者ID:SmartFire,项目名称:SDShare,代码行数:29,代码来源:OdbcCollectionProvider.cs

示例15: ObtenerConexion

        public static OdbcConnection ObtenerConexion()
        {
            mySqlConeccion = new OdbcConnection("Driver={MySQL ODBC 5.3 ANSI Driver};Server=localhost;Database=colchoneria;User=root;Password=; Option=3;");
            mySqlConeccion.Open();

            return mySqlConeccion;
        }
开发者ID:walter016,项目名称:dise2015,代码行数:7,代码来源:CAD.cs


注:本文中的System.Data.Odbc.OdbcConnection类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。