internal OleDbTransaction (OleDbConnection connection, int depth, IsolationLevel isolevel) { this.connection = connection; gdaTransaction = libgda.gda_transaction_new (depth.ToString ()); switch (isolevel) { case IsolationLevel.ReadCommitted : libgda.gda_transaction_set_isolation_level (gdaTransaction, GdaTransactionIsolation.ReadCommitted); break; case IsolationLevel.ReadUncommitted : libgda.gda_transaction_set_isolation_level (gdaTransaction, GdaTransactionIsolation.ReadUncommitted); break; case IsolationLevel.RepeatableRead : libgda.gda_transaction_set_isolation_level (gdaTransaction, GdaTransactionIsolation.RepeatableRead); break; case IsolationLevel.Serializable : libgda.gda_transaction_set_isolation_level (gdaTransaction, GdaTransactionIsolation.Serializable); break; } libgda.gda_connection_begin_transaction (connection.GdaConnection, gdaTransaction); }
public static int SaveRecord(string sql) { const int rv = 0; try { string connectionString = ConfigurationManager.ConnectionStrings["LA3Access"].ConnectionString; using (var conn = new OleDbConnection(connectionString)) { conn.Open(); var cmGetID = new OleDbCommand("SELECT @@IDENTITY", conn); var comm = new OleDbCommand(sql, conn) { CommandType = CommandType.Text }; comm.ExecuteNonQuery(); var ds = new DataSet(); var adapt = new OleDbDataAdapter(cmGetID); adapt.Fill(ds); adapt.Dispose(); cmGetID.Dispose(); return int.Parse(ds.Tables[0].Rows[0][0].ToString()); } } catch (Exception) { } return rv; }
public void BeginTransaction_Connection_Closed () { OleDbConnection cn = new OleDbConnection (); try { cn.BeginTransaction (); Assert.Fail ("#A1"); } catch (InvalidOperationException ex) { // Invalid operation. The connection is closed Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.IsNotNull (ex.Message, "#A4"); } try { cn.BeginTransaction ((IsolationLevel) 666); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Invalid operation. The connection is closed Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); } try { cn.BeginTransaction (IsolationLevel.Serializable); Assert.Fail ("#C1"); } catch (InvalidOperationException ex) { // Invalid operation. The connection is closed Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2"); Assert.IsNull (ex.InnerException, "#C3"); Assert.IsNotNull (ex.Message, "#C4"); } }
public override List<DomainAlias> GetDomainAliases(string domainName) { var _tmp = new List<DomainAlias>(); using (OleDbConnection _conn = new OleDbConnection(Settings.Default.connectionString)) { _conn.Open(); using (OleDbCommand _cmd = new OleDbCommand(@"SELECT domain_aliases.name AS alias, domains.name AS [domain], domain_aliases.status FROM (domain_aliases INNER JOIN domains ON domain_aliases.dom_id = domains.id) WHERE (domain_aliases.status = 0) AND (domains.name = ?)", _conn)) { _cmd.CommandType = CommandType.Text; _cmd.Parameters.AddWithValue("NAME", domainName); using (OleDbDataReader _read = _cmd.ExecuteReader()) { while (_read.Read()) { var _d = new DomainAlias(); _d.Domain = _read["domain"].ToString(); _d.Alias = _read["alias"].ToString(); _tmp.Add(_d); } } } _conn.Close(); } return _tmp; }
public void updateProductPrice(ProductInBag Product) { OleDbConnection myConn = new OleDbConnection(Connstring.getConnectionString()); OleDbCommand myCmd; OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(); try { myCmd = new OleDbCommand("UpdateUnitPrice", myConn); myCmd.CommandType = CommandType.StoredProcedure; OleDbParameter objParam; objParam = myCmd.Parameters.Add("@UnitPrice", OleDbType.Decimal); objParam.Direction = ParameterDirection.Input; objParam.Value = Product.Price; objParam = myCmd.Parameters.Add("@ProductID", OleDbType.Integer); objParam.Direction = ParameterDirection.Input; objParam.Value = Product.ProdID; myConn.Open(); myCmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { myConn.Close(); } }
/** * Constructor that gets the connection to the database and Car information * * @param V VIN of the Car * @param T Type of the Car * @param cn Connection to the database */ public MakeTires(string S, string T, string TS, OleDbConnection cn) { this.SerialNumber = S; this.Type = T; this.TireSize = TS; this.cn = cn; }
protected void Page_Load(object sender, EventArgs e) { System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(); Conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("app_data/productsdb.mdb"); Conn.Open(); //Response.Write(Conn.State); System.Data.OleDb.OleDbCommand Comm = new System.Data.OleDb.OleDbCommand(); System.Data.OleDb.OleDbDataReader dr; Comm.Connection = Conn; Comm.CommandText = "select productid, productname, productiondescription, price, qoh, imagelocation from products"; if (Request.Params["categoryid"] != null && Request.Params["categoryid"].Length >0) { Comm.CommandText += " where categoryid = ?" ; Comm.Parameters.AddWithValue("anything", Request.Params["categoryid"].ToString()); } dr = Comm.ExecuteReader(); bool firstone = true; Response.Write("{\"product\":["); while (dr.Read()) { if (!firstone) { Response.Write(","); } Response.Write(dr[0].ToString()); firstone = false; } Response.Write("]}"); }
private void btn_Browser_Click(object sender, EventArgs e) { OpenFileDialog P_open = new OpenFileDialog();//创建打开文件对话框对象 P_open.Filter = "文本文件|*.txt|所有文件|*.*";//设置筛选字符串 if (P_open.ShowDialog() == DialogResult.OK) { txt_Path.Text = P_open.FileName;//显示文件路径 string conn = string.Format(//创建连接字符串 @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=text", P_open.FileName.Substring(0,P_open.FileName.LastIndexOf(@"\"))); OleDbConnection P_OleDbConnection = new OleDbConnection(conn);//创建连接对象 try { P_OleDbConnection.Open();//打开连接 OleDbCommand cmd = new OleDbCommand(//创建命令对象 string.Format("select * from {0}", P_open.FileName.Substring(P_open.FileName.LastIndexOf(@"\"), P_open.FileName.Length - P_open.FileName.LastIndexOf(@"\"))), P_OleDbConnection); OleDbDataReader oda = cmd.ExecuteReader();//得到数据读取器对象 while (oda.Read()) { txt_Message.Text += oda[0].ToString();//得到文本文件中的字符串 } } catch (Exception ex) { MessageBox.Show(ex.Message);//弹出消息对话框 } finally { P_OleDbConnection.Close();//关闭连接 } } }
/// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public override DataSet ExecuteDataSet(string SQLString, params IDataParameter[] cmdParms) { using (OleDbConnection connection = new OleDbConnection(connectionString)) { OleDbCommand cmd = new OleDbCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (OleDbDataAdapter da = new OleDbDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (OleDbException e) { //LogManage.OutputErrLog(e, new Object[] { SQLString, cmdParms }); throw; } finally { cmd.Dispose(); connection.Close(); } return ds; } } }
protected void Button1_Click(object sender, EventArgs e) { try { OleDbConnectionStringBuilder sb = new OleDbConnectionStringBuilder(); sb.Provider = "Microsoft.ACE.OLEDB.12.0"; sb.DataSource = Server.MapPath("/vedb01/uploads/db1.accdb"); OleDbConnection conn = new OleDbConnection(sb.ConnectionString); conn.Open(); string updateQuery = "UPDATE Bag SET [email protected], [email protected], [email protected], [email protected], [email protected], [email protected] WHERE BagID= @ID"; OleDbCommand com = new OleDbCommand(updateQuery, conn); com.Parameters.AddWithValue("@ID", txtBagId.Text); com.Parameters.AddWithValue("@name", txtBagName.Text); com.Parameters.AddWithValue("@supplier", txtSupplier.Text); com.Parameters.AddWithValue("@color", txtColor.Text); com.Parameters.AddWithValue("@category", txtCategory.Text); com.Parameters.AddWithValue("@price", txtPrice.Text); com.Parameters.AddWithValue("@description", txtDescription.Text); com.ExecuteNonQuery(); lblMessage.Text = "The bag No " + txtBagId.Text +" was updated successfully " + txtBagName.Text + " !"; conn.Close(); } catch (Exception ex) { Response.Write("Error: " + ex.ToString()); lblMessage.Text = "Error !"; } }
protected void btnAddBag_Click(object sender, EventArgs e) { try { OleDbConnectionStringBuilder sb = new OleDbConnectionStringBuilder(); sb.Provider = "Microsoft.ACE.OLEDB.12.0"; sb.DataSource = Server.MapPath("/vedb01/uploads/db1.accdb"); OleDbConnection conn = new OleDbConnection(sb.ConnectionString); conn.Open(); string insertQuery = "insert into Bag ( [BagName], [Supplier], [Color], [Category], [Price], [Description]) values (@name ,@supplier ,@color ,@category ,@price ,@description)"; OleDbCommand com = new OleDbCommand(insertQuery, conn); com.Parameters.AddWithValue("@name", txtBagName.Text); com.Parameters.AddWithValue("@supplier", txtSupplier.Text); com.Parameters.AddWithValue("@color", txtColor.Text); com.Parameters.AddWithValue("@category", txtCategory.Text); com.Parameters.AddWithValue("@price", txtPrice.Text); com.Parameters.AddWithValue("@description", txtDescription.Text); com.ExecuteNonQuery(); lblMessage.Text = "The bag was added successfully " + txtBagName.Text + " !"; conn.Close(); } catch (Exception ex) { Response.Write("Error: " + ex.ToString()); lblMessage.Text = "Error" + txtBagName.Text + " !"; } }
/// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static void ExecuteSqlTran(ArrayList SQLStringList) { using (OleDbConnection conn = new OleDbConnection(connectionString)) { conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; OleDbTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n].ToString(); if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; cmd.ExecuteNonQuery(); } } tx.Commit(); } catch (System.Data.OleDb.OleDbException E) { tx.Rollback(); throw new Exception(E.Message); } } }
protected void Page_Load(object sender, System.EventArgs e) { // resolve the address to the Access database string fileNameString = this.MapPath("."); fileNameString += "..\\..\\..\\..\\data\\chartdata.mdb"; // initialize a connection string string myConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileNameString; // define the database query string mySelectQuery="SELECT GrossSales FROM SALES WHERE QuarterEnding < #01/01/2002#;"; // create a database connection object using the connection string OleDbConnection myConnection = new OleDbConnection(myConnectionString); // create a database command on the connection using query OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection); // open the connection myCommand.Connection.Open(); // create a database reader OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // since the reader implements and IEnumerable, pass the reader directly into // the DataBind method with the name of the Column selected in the query Chart1.Series["Default"].Points.DataBindY(myReader, "GrossSales"); // close the reader and the connection myReader.Close(); myConnection.Close(); }
public void ReadExcelSheet(string fileName, string sheetName, Action<DataTableReader> actionForEachRow) { var connectionString = string.Format(ExcelSettings.Default.ExcelConnectionString, fileName); using (var excelConnection = new OleDbConnection(connectionString)) { excelConnection.Open(); if (sheetName == null) { var excelSchema = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if (excelSchema != null) { sheetName = excelSchema.Rows[0]["TABLE_NAME"].ToString(); } } var excelDbCommand = new OleDbCommand(@"SELECT * FROM [" + sheetName + "]", excelConnection); using (var oleDbDataAdapter = new OleDbDataAdapter(excelDbCommand)) { var dataSet = new DataSet(); oleDbDataAdapter.Fill(dataSet); using (var reader = dataSet.CreateDataReader()) { while (reader.Read()) { actionForEachRow(reader); } } } } }
protected void Button1_Click(object sender, EventArgs e) { int lgflg = 0; OleDbConnection conn = new OleDbConnection(ConfigurationSettings.AppSettings["classDB"]); OleDbCommand cmd = new OleDbCommand("SELECT * FROM student WHERE studentpassword = '" + password.Text + "' AND email = '" + userName.Text + "'", conn); conn.Open(); OleDbDataReader myReader = cmd.ExecuteReader(); while (myReader.Read()) { lgflg = 1; Session.Add("fname", myReader["Contact_name"]); Session.Add("address", myReader["address"]); Session.Add("city", myReader["city"]); Session.Add("state", myReader["state"]); Session.Add("zipcode", myReader["zipcode"]); } myReader.Close(); conn.Close(); if (lgflg == 1) { Response.Write(Session["fname"]); } else { error.Visible = true; } }
public string LoadContain() { if (Request.QueryString["CourseId"] == null) { return string.Empty; } string ThePath = string.Empty; string RetData = string.Empty; using (OleDbConnection Con = new OleDbConnection(constr)) { OleDbCommand cmd = new OleDbCommand(String.Format("SELECT TOP 1 DataPath FROM CoursenotimeDataPath WHERE CourseId = {0}", Request.QueryString["CourseId"]), Con); try { Con.Open(); ThePath = cmd.ExecuteScalar().ToString(); //if (ThePath != string.Empty) // ThePath = MapPath(DB.CourseNoTimeFileDir + ThePath); ThePath = DB.CourseNoTimeFileDir + ThePath; TextReader TR = new StreamReader(ThePath); RetData = TR.ReadToEnd(); TR.Close(); TR.Dispose(); } catch (Exception ex) { RetData = ex.Message; } Con.Close(); } return HttpUtility.HtmlDecode(RetData); }
public DataSet GetDataSet(string filepath, string excelFileExtension) { try { System.Data.OleDb.OleDbConnection oledbcon = null; string strConn = string.Empty; switch (excelFileExtension.Trim()) { case "xls": oledbcon = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1;MaxScanRows=0;\""); strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + "Extended Properties=Excel 8.0;"; break; case "xlsx": oledbcon = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=No;IMEX=1'"); strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0;"; break; } //excel OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); string sheetName = dtSheetName.Rows[0]["TABLE_NAME"].ToString(); System.Data.OleDb.OleDbDataAdapter oledbAdaptor = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", oledbcon); //select DataSet ds = new DataSet(); oledbAdaptor.Fill(ds); oledbcon.Close(); return ds; } catch (Exception ex) { throw ex; } }
protected void btTaiLen_Click1(object sender, EventArgs e) { if (Request.Cookies["ADMIN"] == null) return; if (FileUpload1.HasFile) try { string path = Server.MapPath(@"EXCEL\") + "Question_" + DateTime.Now.ToString("yyMMdd_HHmmss") + ".xlsx"; FileUpload1.SaveAs(path); string txt = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0 Xml;", path); OleDbConnection con = new OleDbConnection(txt); con.Open(); txt = "Select * FROM [Sheet1$]"; OleDbDataAdapter da = new OleDbDataAdapter(txt, con); DataSet ds = new DataSet(); da.Fill(ds); con.Close(); gvCauHoi.DataSource = ds; gvCauHoi.DataBind(); string temp; foreach (GridViewRow dr in gvCauHoi.Rows) { temp = Server.HtmlDecode(dr.Cells[0].Text); if (temp.StartsWith("#")) dr.CssClass = "Q1"; else if (temp.StartsWith("$")) // Không đảo phương án trả lời dr.CssClass = "Q2"; else if (temp.StartsWith("*")) // Phương án trả lời đúng dr.CssClass = "A1"; } } catch (Exception ex) { lbError.Text = ex.Message; } }
private void fill_form(string p_id) { String strQuery = String.Empty; OleDbConnection sqlConn = new OleDbConnection(); OleDbCommand sqlComm = new OleDbCommand(); OleDbDataReader sqlRead;// = new OleDbDataReader(); DateTime strReturn = DateTime.Now; // sqlConn.ConnectionString = PCPUB.m_oledb_connection.ToString(); sqlConn.Open(); // strQuery = String.Empty; strQuery += " SELECT"; strQuery += " [yarn_count_id],"; strQuery += " [yarn_count_name]"; strQuery += " FROM [tis_yarn_count]"; strQuery += " WHERE [yarn_count_id] = '" + p_id + "'"; // sqlComm.Connection = sqlConn; sqlComm.CommandText = strQuery.ToString(); sqlRead = sqlComm.ExecuteReader(); // if (sqlRead.Read()) { txt_yarn_count_id.Text = sqlRead["yarn_count_id"].ToString(); txt_yarn_count_name.Text = sqlRead["yarn_count_name"].ToString(); } // sqlRead.Close(); sqlConn.Close(); sqlRead.Dispose(); sqlComm.Dispose(); sqlConn.Dispose(); }
public DataTable sepetcevir(string uyeID, string map) { OleDbConnection cnn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" + map); cnn.Open(); OleDbCommand cmd = new OleDbCommand("select sepet from uyeler where uyeid=" + uyeID, cnn); OleDbDataReader rdr = cmd.ExecuteReader(); rdr.Read(); string[] urunler = rdr[0].ToString().Split(','); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[3] { new DataColumn("fid"), new DataColumn("aciklama"), new DataColumn("fiyat") }); if (rdr[0].ToString() != "") { foreach (string item in urunler) { cmd.Dispose(); string fid = item; cmd = new OleDbCommand("select * from fotolar where fot_id=" + fid, cnn); OleDbDataReader rdr2 = cmd.ExecuteReader(); rdr2.Read(); string ack = rdr2[5].ToString(); string fiyat = rdr2[6].ToString(); dt.Rows.Add(fid, ack, fiyat); } } cnn.Close(); return dt; }
public void update(string query) { OleDbConnection connection = new OleDbConnection(); string executable = System.Reflection.Assembly.GetExecutingAssembly().Location; string path = (System.IO.Path.GetDirectoryName(executable)); AppDomain.CurrentDomain.SetData("DataDirectory", path); connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/LMS.accdb"; OleDbCommand command; command = connection.CreateCommand(); try { command.CommandText = query; command.CommandType = CommandType.Text; connection.Open(); //SqlCommand comm = new SqlCommand(query, connection); command.ExecuteNonQuery(); } catch (Exception) { } finally { if (connection != null) connection.Close(); } }
private void FormFirma_Load(object sender, EventArgs e) { PutBaze = System.IO.File.ReadAllText(Application.StartupPath + "\\Ponuda\\BazaPonuda.txt"); string PutKriterij =System.IO.File.ReadAllText(@"privPonuda.txt"); string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+PutBaze; //----------SQL instrukcija-----------\\ string sql = "SELECT * FROM sve WHERE Firma LIKE '" + PutKriterij + "%'"; //klase za povezivanje na ACCESS bazu podataka// OleDbConnection conn = new OleDbConnection(connString); OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn); //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ ds = new DataSet(); //kreira noi objekt(kopiju) DataSet()-a conn.Open(); //otvara spoj s bazom podataka adapter.Fill(ds, "sve"); //puni se DataSet s podacima tabele t_razred conn.Close(); //zatvara se baza podataka //nakon zatvaanja BP imamo odgovarajuće podatke u ds objektu ( DataSet() ) dataGridView2.DataSource = ds; //upisivanje podataka id ds u dataGridView2 dataGridView2.DataMember = "sve"; ukupnaCijenaDataGridViewTextBoxColumn.DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("de-DE"); this.dataGridView2.Sort(firmaDataGridViewTextBoxColumn, ListSortDirection.Ascending); System.IO.File.Delete(@"privPonuda.txt"); }
// Gets all the countries that start with the typed text, taking paging into account protected DataTable GetCountries(string text, int startOffset, int numberOfItems) { OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("../App_Data/continent.mdb")); myConn.Open(); string whereClause = " WHERE CountryName LIKE @CountryName"; string sortExpression = " ORDER BY CountryName"; string commandText = "SELECT TOP " + numberOfItems + " CountryID, CountryName FROM Country"; commandText += whereClause; if (startOffset != 0) { commandText += " AND CountryID NOT IN (SELECT TOP " + startOffset + " CountryID FROM Country"; commandText += whereClause + sortExpression + ")"; } commandText += sortExpression; OleDbCommand myComm = new OleDbCommand(commandText, myConn); myComm.Parameters.Add("@CountryName", OleDbType.VarChar).Value = text + '%'; OleDbDataAdapter da = new OleDbDataAdapter(); DataSet ds = new DataSet(); da.SelectCommand = myComm; da.Fill(ds, "Country"); myConn.Close(); return ds.Tables[0]; }
private void addToDatabase(string sql) { OleDbConnection db = null; try { db = new OleDbConnection(); db.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + mFileName; db.Open(); OleDbCommand command = new OleDbCommand(sql, db); command.ExecuteNonQuery(); } catch (Exception ex) { showErrorMessage(ex.Message); } finally { if (db != null) { db.Close(); } } }
//Create an Excel file with 2 columns: name and score: //Write a program that reads your MS Excel file through //the OLE DB data provider and displays the name and score row by row. static void Main() { OleDbConnection dbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=D:\Telerik\DataBases\HW\ADONET\06. ReadExcel\Table.xlsx;Extended Properties=""Excel 12.0 XML;HDR=Yes"""); OleDbCommand myCommand = new OleDbCommand("select * from [Sheet1$]", dbConn); dbConn.Open(); //First way //using (dbConn) - I think it is better to use dbConn in using clause, but for the demo issues i dont use using. //{ OleDbDataReader reader = myCommand.ExecuteReader(); while (reader.Read()) { string name = (string)reader["Name"]; double score = (double)reader["Score"]; Console.WriteLine("{0} - score: {1}", name, score); } //} dbConn.Close(); //Second way dbConn.Open(); Console.WriteLine(); Console.WriteLine("Second Way"); Console.WriteLine("----------"); DataTable dataSet = new DataTable(); OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [Sheet1$]", dbConn); adapter.Fill(dataSet); foreach (DataRow item in dataSet.Rows) { Console.WriteLine("{0}|{1}", item.ItemArray[0], item.ItemArray[1]); } dbConn.Close(); }
public ReservationForm() { reservationConn = new OleDbConnection(connString); drawPanel(); drawPlan(); InitializeComponent(); }
private static void PrintSpreadsheet(OleDbConnectionStringBuilder connestionString) { DataSet sheet1 = new DataSet(); using (OleDbConnection connection = new OleDbConnection(connestionString.ConnectionString)) { connection.Open(); string selectSql = @"SELECT * FROM [Sheet1$]"; using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection)) { adapter.Fill(sheet1); } connection.Close(); } var table = sheet1.Tables[0]; foreach (DataRow row in table.Rows) { foreach (DataColumn column in table.Columns) { Console.Write("{0, -20} ", row[column]); } Console.WriteLine(); } }
public List<MonthlyExpenseReportItem> cercaMovimentiCategoria(int idCat) { OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.scadenzettiDbConnectionString); string queryString = "SELECT * FROM QueryReportCategoria"; OleDbCommand cmd = new OleDbCommand(queryString, conn); cmd.Parameters.Add("idCat", OleDbType.Integer).Value = idCat; conn.Open(); OleDbDataReader reader = cmd.ExecuteReader(); List<MonthlyExpenseReportItem> list = new List<MonthlyExpenseReportItem>(); while (reader.Read()) { MonthlyExpenseReportItem mov = new MonthlyExpenseReportItem(); mov.Scadenza = DateTime.Parse(reader[0].ToString()); mov.Importo = decimal.Parse(reader[1].ToString()); mov.Debitore = reader[2].ToString(); mov.Creditore = reader[3].ToString(); mov.Causale = reader[4].ToString(); mov.Tipo = reader[5].ToString(); mov.Ultimato = bool.Parse(reader[6].ToString()); list.Add(mov); } reader.Close(); conn.Close(); return list; }
public bool InsertFtpRecord(FileDetail fileDetail) { var lcsql = "insert into MasterFtp(FileName, CreateTime, Folder, Records, DlTime) values ( ?, ?,?,?,?)"; var connectionString = ConfigurationManager.ConnectionStrings["vfpConnectionString"].ConnectionString; using (var connection = new OleDbConnection(connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SET NULL OFF"; command.ExecuteNonQuery(); } using (var command = connection.CreateCommand()) { command.CommandText = lcsql; command.Parameters.AddWithValue("FileName", fileDetail.FileName); command.Parameters.AddWithValue("CreateTime", fileDetail.FileDate); command.Parameters.AddWithValue("Folder", fileDetail.Folder); command.Parameters.AddWithValue("Records", fileDetail.Records); command.Parameters.AddWithValue("DlTime", fileDetail.DownloadTime); //connection.Open(); var retval = command.ExecuteNonQuery(); var success = (retval == 1); return success; } } }
public IDataReader ExecuteDataReader(string connectionString, string query) { _connection = new OleDbConnection(connectionString); _connection.Open(); var command = new OleDbCommand(query, _connection); return command.ExecuteReader(); }