Insert data into Access database with visual studio 2012 - basic

I'm trying to insert data into Oradores Table in Access using Visual Basic. The code I have is:
'Public Variables
novo_nome_comum = TxtNComum.Text
novo_nome_completo = TxtNCompleto.Text
nova_morada = TxtMorada.Text
nova_localidade = TxtLocalidade.Text
novo_codpostal = TxtCPostal.Text
novo_tel1 = TxtTel1.Text
novo_tel2 = TxtTel2.Text
novo_tlm1 = TxtTlm1.Text
novo_tlm2 = TxtTlm2.Text
novo_email1 = TxtMail1.Text
novo_email2 = TxtMail2.Text
nova_cong = TxtCong.Text
'End of Public Variables
Dim connect As New OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;" & "Data Source =C:\Users\Fernando\Documents\Visual Studio 2012\Projects\Agenda_DP\Agenda_DP\AgendaDP.accdb")
connect.Open()
Dim cmd As OleDbCommand = connect.CreateCommand()
cmd.CommandText = "INSERT INTO Oradores (NomeComum, NomeCompleto, Morada, Localidade, CodPostal, Telefone, Telefone2, Telemovel, Telemovel2, email, email2, Congregacao) VALUES('novo_nome_comum', 'novo_nome_completo', 'nova_morada', 'nova_localidade', 'novo_codpostal', 'novo_tel1', 'novo_tel2','novo_tlm1', 'novo_tlm2', 'novo_email1', 'novo_email2', 'nova_cong')"
cmd.ExecuteNonQuery()
connect.Close()
However, this is not working, and I don't understand why.
I searched in MSDN and I'm copying the example quoted to my code.
Is there anyone who could give me an hand?
Thanks in advance.
Fernando Pessoa

I will share you a piece of code:
Try
Dim con As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=yourDB.accdb;")
Dim cb As String = "insert into Table1 (Date1, Sample1) VALUES (#p1, #p2)"
Dim cmd As New System.Data.OleDb.OleDbCommand
cmd.Connection = con
cmd.CommandText = cb
cmd.Parameters.AddWithValue("#p1", Me.DateTimePicker1.Value.ToShortDateString())
cmd.Parameters.AddWithValue("#p2", Me.TextBox1.Text)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Catch ex As Exception
MessageBox.Show(Err.Description)
End Try
It is working fine in my sample.
You can visit a post called MS Access - VB .net - connect and operate

Related

How to skip rows while importing ExcelSheet with variable sheetname?

I have to import ExcelSheets with variable Sheetnames via SSIS. Sheetname is determined by scripttask and passed via User::Variable to ExcelSource. The problem is that data/headline always starts at row 11.
How is it possible to pass something like "$A10:AB50" (required data selection) to the sheetname delivered in User::Variable?
I´ve already tried to pass the required data-selection-string (e.g. "$A10:AB50") to OpenRowsetVariable, ExcelConnectionManager, ConnectionString... without success. I also tried skipping/splitting first 10 rows via conditional split, but couldn`t find any approach to this.
A test with a second ConnectionManager getting data from a defined file and that has data access via sql-query (e.q. "select f1,f2... from [sheetname$a1:ab50]") works great indeed.
This is how scripttask determines sheetname:
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FILEPATH + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname = "";
foreach (DataRow drSheet in dtSheet.Rows)
{
// sheetname only
if (drSheet["TABLE_NAME"].ToString().Contains("$") && !drSheet["TABLE_NAME"].ToString().Contains("Print_Area"))
{
sheetname = drSheet["TABLE_NAME"].ToString();
// return sheetname
//MessageBox.Show(sheetname);
Dts.Variables["User::rSheetName"].Value = sheetname;
Solved!
Simply added the decided data selection to the sheet-return-variable in scripttask:
if (drSheet["TABLE_NAME"].ToString().Contains("$") && !drSheet["TABLE_NAME"].ToString().Contains("Print_"))
{
SheetName = drSheet["TABLE_NAME"].ToString();
// concat datazone to sheetname
DataZone = "A10:AB50";
SnameValue = SheetName + DataZone;
SnameValue = SnameValue.Replace(#"'", "");
// return combined sheetname
MessageBox.Show(SnameValue);
Dts.Variables["User::rSheetName"].Value = SnameValue;
cnn.Close();
}
It was way to easy... thanks for thinking about it anyway ;-)

Allowing VB.NET app to convert Excel Files to Datatable

My VB.NET app currently allows me to convert CSV files to a datatable thanks to the code provided by David in this question I posted: Previous Question
Now I am trying to allow .XLSX files to be imported to a datatable as well. Currently the code looks like this:
Private Function ConvertCSVToDataTable(ByVal path As String) As DataTable
Dim dt As DataTable = New DataTable()
Using con As OleDb.OleDbConnection = New OleDb.OleDbConnection()
Try
If System.IO.Path.GetExtension(path) = ".csv" Then
con.ConnectionString = String.Format("Provider={0};Data Source={1};Extended Properties=""Text;HDR=YES;FMT=Delimited""", "Microsoft.Jet.OLEDB.4.0", IO.Path.GetDirectoryName(path))
ElseIf System.IO.Path.GetExtension(path) = ".xlsx" Then
con.ConnectionString = String.Format("Provider={0};Data Source={1};Extended Properties=""Excel 12.0 XML;HDR=Yes;""", "Microsoft.ACE.OLEDB.12.0", IO.Path.GetDirectoryName(path))
End If
Using cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM " & IO.Path.GetFileName(path), con)
Using da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(cmd)
con.Open()
da.Fill(dt)
con.Close()
End Using
End Using
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
If con IsNot Nothing AndAlso con.State = ConnectionState.Open Then
con.Close()
End If
End Try
End Using
Return dt
End Function
However, when I run the code using the .XLSX file, I get the following error:
{"The Microsoft Office Access database engine cannot open or write to
the file 'C:\Users\XSLXFilePath'. It is already opened exclusively by
another user, or you need permission to view and write its data."}
The file is not open anywhere else to my knowledge. And the app also runs fine when .CSV file is put through it instead. How do I get the app to properly work for .XLSX, or any Excel file format?
I think that the error is that from the connection string and the OLEDB Command:
ConnectionString
You don't have to use IO.Path.GetDirectoryName(path) it returns the directory name, you have to provide the file full path:
con.ConnectionString = String.Format("Provider={0};Data Source={1};Extended Properties=""Excel 12.0 XML;HDR=Yes;""", "Microsoft.ACE.OLEDB.12.0", path)
Refer to this link for excel connectionstring generation function: import data from excel 2003 to dataTable
OLEDB Command
You must provide the Worksheet name in the Command instead of the Filename:
Using cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM [Sheet1$]" , con)
If the Sheet names is dynamic and you have to get the first sheet in the excel file:
Dim dbSchema as DataTable = con.GetOleDbSchemaTable (OleDbSchemaGuid.Tables, null)
Dim firstSheetname as String = dbSchema.Rows(0)("TABLE_NAME").ToString
Using cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM [" & firstSheetname & "]" , con)
References
Reading from excel using oledbcommand
Read and Write Excel Documents Using OLEDB
Use can use the following connection string for .xlsx file.
I have used it and working fine.
P_FIle = ( File Name with path )
P_Con_Str = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & P_File & ";Extended Properties=""Excel 12.0 XML;HDR=Yes;"""

Visual Studio 2012 OLEDB connection

I have this code that I am using in visual studio 2012 to populate a combobox from data in a sql database. Every time I try to debug it I get the exception at the for loop of a null reference exception. I am hoping someone can help me figure out what it is I am missing here.
Private Sub StationList_Click(sender As Object, e As EventArgs) Handles StationList.Click
Dim cn As New OleDbConnection
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hendera2\Desktop\StationEquip.accdb"
Dim Mystr As String = "SELECT DISTINCT Location FROM StationEquipment"
Dim Myadapter As OleDbDataAdapter
Dim Mydataset As New DataSet()
Try
cn.Open()
Myadapter = New OleDbDataAdapter(Mystr, cn.ConnectionString)
Myadapter.Fill(Mydataset, Mystr)
Dim dr As DataRow
For Each dr In Mydataset.Tables("StationEquipDataSet").Rows
Me.StationList.Items.Add(dr("Location"))
Next
cn.Close()
Catch ex As Exception
MsgBox("Cannot Open connection")
End Try
End Sub
Change the "StationEquipDataSet" data table name to "StationEquipment"
You're mismatching the table name, this is causing the null reference when you're trying to access the rows of this table, because it doesnt exists
Obviously I can't see your database, or the records it's pulling, but I would try adding this to elemenate the possibility of trying to reference a null value:
If Mydataset.Tables("StationEquipDataSet").Rows.Count > 0 Then
For Each dr In Mydataset.Tables("StationEquipDataSet").Rows
Me.StationList.Items.Add(dr("Location"))
Next
End If
I believe you got the name wrong in the Mydataset.Tables("StationEquipDataSet") expression.
To find out whether the dataset really does contain your table, and to find out what would be the correct name to use as index, you could try to insert these lines just before the loop:
Console.WriteLine(MyDataSet.Tables.Count);
for (var i = 0; i > MyDataSet.Tables.Count;i++)
{
Console.WriteLine(MyDataSet.Tables[0].TableName);
}
This would for instance write the amount of tables and the table names to the console.

query for reading data from excel sheet in c#

Thanks Astander for replying to my query
I am here with more detailed query.
string cs = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + #"D:\\sample.xls;" + "Excel 12.0;HDR=YES;";
OleDbConnection Excelcon = new OleDbConnection(cs);
OleDbDataAdapter ad = new OleDbDataAdapter();
ad.SelectCommand = new OleDbCommand("SELECT *FROM [Sheet1$]", Excelcon);
DataTable dt = new DataTable();
ad.Fill(dt);
return dt;
I am getting error at the select statement that :
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly.
Hope someone can help me find a solution.
What worked for me is,
when file was created, it was stored in some specific location. In my case,C:/Documents.
I had manually changed the location to D:
this was what I had written
string connStringExcel = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\example.xls;Extended Properties=""Excel 12.0;HDR=YES;""";`
So,the actual path should be
string connStringExcel = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\A\Documents\example.xls;Extended Properties=""Excel 12.0;HDR=YES;""";`
So on giving the path of correct location,my query was solved.
Hope it helps someone else too.
// Create connection string variable. Modify the "Data Source"
// parameter as appropriate for your environment.
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("../ExcelData.xls") + ";" +
"Extended Properties=Excel 8.0;";
// Create connection object by using the preceding connection string.
OleDbConnection objConn = new 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.
OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM myRange1", objConn);
// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;
// Create new DataSet to hold information from the worksheet.
DataSet objDataset1 = new DataSet();
// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData");
// Bind data to DataGrid control.
DataGrid1.DataSource = objDataset1.Tables[0].DefaultView;
DataGrid1.DataBind();
// Clean up objects.
objConn.Close();
ref to thisLink

Reading Excel file w/ADO.net - no data (or tables)

This is my first attempt to read an Excel 2007 file via ADO.net, and I must be missing something b/c when I try to run the query, I get an exception. When I started looking, it's b/c the table (worksheet) isn't there. Can someone please tell me what I'm doing wrong?
Here is my code:
string cs = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=My File.xlsx;Extended Properties=""Excel 12.0;IMEX=1;""";
using (OleDbConnection con = new OleDbConnection(cs))
{
con.Open();
string query = "SELECT * FROM [Sheet1$]";
OleDbCommand cmd = new OleDbCommand(query, con);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
DataTable worksheets = con.GetSchema("Tables");
adapter.Fill(dt);
.
.
.
}
Take a look at the accepted answer here
The First Column of the excel file to put in string variable C#?
It works for Excel 2003 but I think it could easily be adapted to work with 2007.

Resources