读mdb数据库中的表,返回datatable;链接postgresql数据库,读取数据库中表

    xiaoxiao2021-12-04  19

    public DataTable ReadMDB(string mdbFile,string tableName) { string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + mdbFile; OleDbConnection conn = new OleDbConnection(connStr); conn.Open(); //[]符号是为了支持表明带有横线的情况 string queryPiles = "select * from ["+ tableName+"]"; OleDbCommand cmd = conn.CreateCommand(); cmd.CommandText = queryPiles; OleDbDataReader oleReader = cmd.ExecuteReader(); DataTable dt = new DataTable(); int colSize = oleReader.FieldCount; for (int i = 0; i < colSize; i++) { DataColumn col = new DataColumn(oleReader.GetName(i)); dt.Columns.Add(col); } DataRow dr; while (oleReader.Read()) { dr = dt.NewRow(); string colName; string colValue; for (int j = 0; j < colSize; j++) { colName = oleReader.GetName(j); colValue = oleReader[colName].ToString(); dr[colName] = colValue; } dt.Rows.Add(dr); } oleReader.Close(); conn.Close(); return dt; }

    一言不合就上代码

    2.链接postgresql数据库,读取数据库中表

    NpgsqlConnection conn; private void btn_connPostGIS_Click(object sender, EventArgs e) { string ip = tbx_ip.Text.Trim(); string port = tbx_port.Text.Trim(); string userName = tbx_user.Text.Trim(); string pass = tbx_password.Text.Trim(); string dbName = tbx_db.Text.Trim(); if (ip == "" || port == "" || userName == "" || pass == "" || dbName == "") { MessageBox.Show("数据库连接信息不完整,请检查重新输入。"); return; } //获取用户自定义的表 string selectAllTabelStr = "SELECT tablename From pg_tables WHERE schemaname='public';"; string connStr = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};",ip,port,userName,pass,dbName); conn = new NpgsqlConnection(connStr); conn.Open(); NpgsqlDataAdapter pAdapter = new NpgsqlDataAdapter(selectAllTabelStr, conn); DataSet ds = new DataSet(); pAdapter.Fill(ds); DataTable tableNames = ds.Tables[0]; List<string> nameList = new List<string>(); foreach (DataRow dr in tableNames.Rows) { nameList.Add(dr[0].ToString()); } cbx_tableName.DataSource = nameList; } private void btn_OK_Click(object sender, EventArgs e) { if (conn == null) return; string tblName = cbx_tableName.Text; if (tblName == "") { MessageBox.Show("请选择用于建模的数据表."); return; } string selectDataStr = "SELECT * FROM " + tblName + ";"; NpgsqlDataAdapter pAdapter = new NpgsqlDataAdapter(selectDataStr, conn); DataSet ds = new DataSet(); pAdapter.Fill(ds); mTable = ds.Tables[0]; conn.Close(); this.DialogResult = DialogResult.OK; }

    转载请注明原文地址: https://ju.6miu.com/read-680339.html

    最新回复(0)