Can someone explain to me why it wont allow me to insert my record into MS Access?
for some reason i have tried everything that is humanly possible but it wont let me do what i need to do. what i need to do is allow record to be written from my c Sharp program and would want to press a button which will insert the value into my MS Access.
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "INSERT INTO BookKey, Title, Pages from Books;";
OleDbConnection conn = new OleDbConnection(dbconnection);
OleDbCommand comm = new OleDbCommand(dbcommand, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
conn.Open();
adapter.Fill(ds, "Books");
conn.Close();
DataTable dt = ds.Tables[0];
//define a new record and place it into a new DataRow
DataRow newRow = dt. NewRow();
newRow["BookKey"] = txtBookKey.Text;
newRow["Title"] = txtTitle.Text;
newRow["Pages"] = txtPages.Text;
//add the new DataRow to DataTable
dt.Rows.Add(newRow);
//update DB
adapter.Update(ds, "Books");
//accept changes
ds.AcceptChanges();
//update listBox1
lstDisplayBooks.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
lstDisplayBooks.Items.Add(row["BookKey"] + " " + row["Title"] + " (" + row["Pages"] + ")");
}
txtBookKey.Enabled = false;
txtBookKey.Text = " ";
txtTitle.Enabled = false;
txtTitle.Text = " ";
txtPages.Enabled = false;
txtPages.Text = " ";
btnInsert.Enabled = false;
}
An OleDbDataAdapter need a SELECT query and an OleDBCommandBuilder to generate automatically the INSERT/UPDATE/DELETE commands that will be used in the Update method
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "SELECT * FROM Books;";
using(OleDbConnection conn = new OleDbConnection(dbconnection))
using(OleDbCommand comm = new OleDbCommand(dbcommand, conn))
{
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
// See comments below for these properties
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
conn.Open();
adapter.Fill(ds, "Books");
DataTable dt = ds.Tables[0];
DataRow newRow = dt. NewRow();
newRow["BookKey"] = txtBookKey.Text;
newRow["Title"] = txtTitle.Text;
newRow["Pages"] = txtPages.Text;
dt.Rows.Add(newRow);
builder.GetInsertCommand();
adapter.Update(ds, "Books");
}
//update listBox1
lstDisplayBooks.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
lstDisplayBooks.Items.Add(row["BookKey"] + " " + row["Title"] + " (" + row["Pages"] + ")");
}
txtBookKey.Enabled = false;
txtBookKey.Text = " ";
txtTitle.Enabled = false;
txtTitle.Text = " ";
txtPages.Enabled = false;
txtPages.Text = " ";
btnInsert.Enabled = false;
}
The example in the link for the OleDbCommandBuilder contains an example like this.
The code should fix your initial error, but really there is no need to use an OleDbDataAdapter in this scenario. If your only objective is just to add a new record to the datatable and you don't need to maintain a local datasource like a DataGridView it is a lot simpler to use directly the OleDbCommand with an appropriate written INSERT and parameterized query
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "INSERT INTO Books (BookKey, Title, Pages) VALUES(?,?,?);";
using(OleDbConnection conn = new OleDbConnection(dbconnection))
using(OleDbCommand comm = new OleDbCommand(dbcommand, conn))
{
conn.Open();
comm.Parameters.AddWithValue("#p1", txtBookKey.Text);
comm.Parameters.AddWithValue("#p2", txtTitle.Text);
comm.Parameters.AddWithValue("#p3", txtPages.Text);
comm.ExecuteNonQuery();
}
.....
Related
I want to connect to multiple databases and want to run some query on through those connections, but it's not working.
string source = "10.0.0.0";
string user = "abc";
string password="abc";
DataTable dt = new DataTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
string source = dt.Rows[i][2].ToString();
string user = dt.Rows[i][1].ToString();
int password = Convert.ToInt32(user) + 111;
OracleConnection conn = new OracleConnection("Data Source = " + source + ": 1521/rms; User id = " + user + "; Password=" + password + ";");
conn.Open();
OracleCommand cmd = new OracleCommand(" SELECT SUM(AI_TRN) FROM tr_rtl where DC_DY_BSN = '06-04-2016'and mall like '%" + Mallname.Text + "%' ", conn);
cmd.ExecuteNonQuery();
OracleDataAdapter oda = new OracleDataAdapter(cmd);
oda.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
label1.Text = source;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
sorry i have posted the wrong code
What you probably will need to do is iterate through a list of connections and populate one data table with all the results. Here is an example:
List<OracleConnections> Connections = new List<OracleConnections>();
DataTable FinalResults = new DataTable();
foreach (var Connection in Connections)
{
using (Connection)
{
DataTable TemporaryTable = new DataTable();
Connection.Open();
OracleCommand Command = new OracleCommand("SomeCommandText", Connection);
OracleDataAdapter Adapter = new OracleDataAdapter(Command);
Adapter.Fill(TemporaryTable);
FinalResults.Merge(TemporaryTable);
}
}
This should give you all the results of each database/connection in one final table (Results) or you can do a dataset if it is different columns/data within each connection.
Updated to explain comments listed above.
string Source = "10.0.0.0";
string User = "abc";
string Password = "abc";
DataTable dt = new DataTable();
// Remove this or use another reference (different table), you just created the table ^, it has no rows. -> "for (int i = 0; i < dt.Rows.Count; i++)"
I have a method that displays the entire schema of an MS Access table into a datagridview control. How would I be able to display just the column name and data type schema columns in the datagridview. The method that I am working with is below. Thank you for any advice.
private void ButtonFieldHelp_Click(object sender, EventArgs e)
{
char ch = '"';
dbConn = new OleDbConnection();
dbCmd = new OleDbCommand();
DataTable data;
OleDbDataReader reader;
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + this.stringData + ch;
dbConn.Open();
dbCmd.Connection = dbConn;
dbCmd.CommandText = "SELECT * FROM " + this.comboBox.SelectedItem.ToString();
reader = dbCmd.ExecuteReader();
foreach (DataRow tableField in data.Rows)
{
foreach (DataColumn tableProperty in data.Columns)
{
dataGridView.DataSource = data;
}
}
this.txtRecords.Text = data.Rows.Count.ToString();
reader.Close();
dbConn.Close();
}
Here is your code modified to work as you need using OleDbDataAdapter:
private void ButtonFieldHelp_Click(object sender, EventArgs e)
{
char ch = '"';
var dbConn = new OleDbConnection();
var dbCmd = new OleDbCommand();
DataTable data = new DataTable();
OleDbDataReader reader;
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + this.stringData + ch;
dbConn.Open();
dbCmd.Connection = dbConn;
dbCmd.CommandText = "SELECT * FROM " + this.comboBox.SelectedItem.ToString();
//reader = dbCmd.ExecuteReader();
OleDbDataAdapter adapter = new OleDbDataAdapter(dbCmd);
adapter.Fill(data);
var dataTable = new DataTable();
dataTable.Columns.Add("ColumnName");
dataTable.Columns.Add("ColumnType");
foreach (DataColumn column in data.Columns)
{
dataTable.Rows.Add(column.ColumnName, column.DataType.ToString());
}
this.dataGridView1.DataSource = dataTable;
this.txtRecords.Text = data.Rows.Count.ToString();
dbConn.Close();
}
My question is how can i export gridview into MS Access in C#
for this I am Using the following code:
String accessConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\...\\test.accdb;";
String sqlConnectionString = ConfigurationManager.ConnectionStrings["College"].ConnectionString;
//Make adapters for each table we want to export
SqlDataAdapter adapter1 = new SqlDataAdapter();
// SqlDataAdapter adapter2 = new SqlDataAdapter();
DataTable dtFillGrid = (DataTable)ViewState["FillGrid"];
//Fills the data set with data from the SQL database
// DataSet dataSet = new DataSet();
adapter1.Fill(dtFillGrid);
// adapter2.Fill(dataSet, "Table2");
//Create an empty Access file that we will fill with data from the data set
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.Create(accessConnectionString);
//Create an Access connection and a command that we'll use
OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = accessConnection;
command.CommandType = CommandType.Text;
accessConnection.Open();
//This loop creates the structure of the database
foreach (DataTable table in dtFillGrid.Rows)
{
String columnsCommandText = "(";
foreach (DataColumn column in table.Columns)
{
String columnName = column.ColumnName;
String dataTypeName = column.DataType.Name;
String sqlDataTypeName = getSqlDataTypeName(dataTypeName);
columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
}
columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
columnsCommandText += ")";
command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;
command.ExecuteNonQuery();
}
//This loop fills the database with all information
foreach (DataTable table in dtFillGrid.Rows)
{
foreach (DataRow row in table.Rows)
{
String commandText = "INSERT INTO " + table.TableName + " VALUES (";
foreach (var item in row.ItemArray)
{
commandText += "'" + item.ToString() + "',";
}
commandText = commandText.Remove(commandText.Length - 1);
commandText += ")";
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}
accessConnection.Close();
but in this code I get an error:
The Type or Namespace name ADOX could not be found
According to accessConnectionString content you should install "Data Connectivity Components" in your machine.
It is available to download at http://www.microsoft.com/en-us/download/details.aspx?id=23734
You need to add a reference for Microsoft ADO Ext. 2.7 for DDL and Security(the version number may be different though) which can be found under the COM section of the references dialog , and then add using ADOX; in your code.
Here I did not export gridview in MS Access but I made a database in MS Access using C# with the help of this code
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;
I want to export grid to MS Access in C#
Here's the code that I've tried:
String accessConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\\...\\test.accdb;";
String sqlConnectionString = ConfigurationManager.ConnectionStrings["College"].ConnectionString;
SqlDataAdapter adapter1 = new SqlDataAdapter();
adapter1.Fill(dtFillGrid);
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.Create(accessConnectionString);
OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = accessConnection;
command.CommandType = CommandType.Text;
accessConnection.Open();
foreach (DataTable table in dtFillGrid.Rows) {
String columnsCommandText = "(";
foreach (DataColumn column in table.Columns) {
String columnName = column.ColumnName;
String dataTypeName = column.DataType.Name;
String sqlDataTypeName = getSqlDataTypeName(dataTypeName);
columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
}
columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
columnsCommandText += ")";
command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;
command.ExecuteNonQuery();
}
//This loop fills the database with all information
foreach (DataTable table in dtFillGrid.Rows) {
foreach (DataRow row in table.Rows) {
String commandText = "INSERT INTO " + table.TableName + " VALUES (";
foreach (var item in row.ItemArray) {
commandText += "'" + item.ToString() + "',";
}
commandText = commandText.Remove(commandText.Length - 1);
commandText += ")";
command.CommandText = commandText; command.ExecuteNonQuery();
}
}
accessConnection.Close();
How can I do this?
I would suggest you create the MDB database, create the table(s) you want using sql, then at runtime bind the gridview, or loop through the results and do a batch import.
See here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms677200(v=vs.85).aspx
using ADOX; // add a COM reference to "Microsoft ADO Ext. x.x for DDL and Security"
static void CreateMdb(string fileNameWithPath)
{
ADOX.Catalog cat = new ADOX.Catalog();
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5";
cat.Create(String.Format(connstr, fileNameWithPath));
cat = null;
}
if you dont have problem with payement you can use 'Spire doc' to save datagrid into msAccess like so :
private void btnExportToAccess_Click(object sender, EventArgs e)
{
Spire.DataExport.Access.AccessExport accessExport = new
Spire.DataExport.Access.AccessExport();
accessExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
accessExport.DataTable = this.dataGridView1.DataSource as DataTable;
accessExport.DatabaseName = #"..\..\ToMdb.mdb";
accessExport.TableName = "ExportFromDatatable";
accessExport.SaveToFile();
}
and Here a link where you can find more clarification
Here I am not export gridview in MS Access but I made a database in MS Access by using C# with the help of this code:
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;
Yes I tell you to all of you that we don't need to export data by gridview to MS Access , we can do this directly create database in MS Access using C#
I have one excel sheet from which I am getting data in dataset using OleDbConnection
private static DataSet ImportExcel(string FileName, bool hasHeaders)
{
string HDR = hasHeaders ? "Yes" : "No";
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName +
";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\"";
DataSet output = new DataSet();
using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow row in dt.Rows)
{
string sheet = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
}
return output;
}
Now I want to Insert data from this dataset to sqlite table.
This is how we can do it
SQLiteConnection m_dbConnection;
void createDbAndTable()
{
SQLiteConnection.CreateFile("MyDatabase.sqlite");
m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite; Version=3;");
m_dbConnection.Open();
string sql = "create table myValues (name varchar(20), highScore int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
void fillTable(DataSet ds)
{
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var name = dr["name"].ToString();
var score = Convert.ToInt32(dr["value"].ToString());
string sql = "insert into myValues (name, highScore) values ( '" + name + "'," + score + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}