This question already has answers here:
How to create Microsoft Access database in C# programmatically?
(4 answers)
Closed 7 years ago.
How can I create a ms access database in C#?
I have created an application using which I can drain some specific information about hardware and software now I want to create a database and write those information to an Access database file!
I have never used c# to create a database, but this maybe helpful:
https://support.microsoft.com/nl-nl/kb/149558
I have used an existing Access database in combination with c#.
The connectionprovider below may vary on the Access version. Here are some connectionstrings: https://www.connectionstrings.com/access/
//Making the connection
string databaseLocation = "location";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + databaseLocation);
//Opening the connection
con.Open();
//Making a command
OleDbCommand odc = new OleDbCommand("query",con);
//Execute a select query
OleDbDataReader reader = odc.ExecuteReader();
//Example of retrieving data from select query
while(reader.Read())
{
string result = reader.getString(0);
}
//Execute different query (examples: insert into, update, delete)
odc.ExecuteNonQuery();
//Closing the connection
con.Close();
I hope it helps!
Related
I have a c# winform project that supposes to save data to SQLite database, I've already used the dll properly and it runs without error, but I get an exception when trigger the method with buttonClick event
here the exception i got : Keyword not supported :'version'.
this the connection string:
"Data Source = Diary.db;Version = 3;New = False;Compress = True;";
and this the complete method :
private void AddToDbaseSQL3()
{
try{
string query = "insert into Diary(title,date,mood,wheater,content)
values('"+TitleTextbox.Text+"','"
+dateTimePicker.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','"
+MoodCombobox.SelectedItem+"','"
+WheaterCombobox.SelectedItem+"','"
+ContentTextbox.Text+"');";;
SqlConnection connect2 = new SqlConnection(connection2);
SqlCommand cmd = new SqlCommand(query,connect2);
SqlDataReader read;
connect2.Open();
read = cmd.ExecuteReader();
while(read.Read())
{
}
MessageBox.Show("created");
TitleTextbox.Text = "Title";
TitleTextbox.ForeColor = SystemColors.ControlLight;
ContentTextbox.Clear();
connect2.Close();
}catch(Exception e){
MessageBox.Show(e.Message);
}
}
I've looked to this link:
Keyword not supported: 'version'
and it said to change SqlConnection to SQLiteConnection but it ended with an error, can you tell what's is the right connection string ? or there is something wrong from my code/method? please tell me, thank you, I'm sorry because it's my first time using the SQLite
SqlConnection from System.Data.SqlClient is for SQL Server.
You need an dedicated SQLite ADO.NET provider.
You can found the System.Data.SQLite provider from SQLite team here:
https://system.data.sqlite.org
Or you can use any libre or commercial provider.
You can also use the free and open-source SQLite ODBC driver that works fine and allow to use VS Visual Designers to create strongly typed ADO.NET DataSets, in addition to the use of OdbcConnection, OdbcCommand and so on:
http://www.ch-werner.de/sqliteodbc
C# Reading data from existing SQLite database
I googled for half a day how to set the path of my database so if I put it on an other computer it will work. I would keep googling but I really need the answer really fast... I'll have to use it to a competition in few hours.
string path = Path.Combine(Application.StartupPath, "Database1.mdf");
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + path + ";");
conn.Open();
SqlCommand command = new SqlCommand("SELECT NAME FROM DATA", conn);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string text = reader.GetString(0);
MessageBox.Show(text);
}
SqlCommand c = new SqlCommand("INSERT INTO DATA (id, name) VALUES(i, v)", conn);
c.Parameters.AddWithValue("#i", 1);
c.Parameters.AddWithValue("#v", "Jack");
c.ExecuteNonQuery();
conn.Dispose();
This code is working for selection but not for insertion. Then I hardcoded the path into:
String s = #"C:\Users\Radu\Documents\Visual Studio 2013\Projects\WindowsFormsApplication7\WindowsFormsApplication7\Database1.mdf";
and it works for both so it's not the SQL statement that is wrong.
So my question is: what is the path I should put into my SqlConnection object so that when they get my source code on my competition and test it on another pc it will work.
LocalDB is meant exclusively for development. You cannot use it in production. In your case, 'production' means the competition. Unless the competition organizer specifies that they support a SQL Server instance for you to connect to, and give out the connection parameters (ie. very unlikely), you shouldn't use use SQL Server in your project.
You can put the MDF file on any file share that your computer has access to. Just alter the path variable to point at the correct file share.
See answers to your question here Can SQL Server Express LocalDB be connected to remotely?
This question already has answers here:
How do I connect to a SQL database from C#?
(9 answers)
Closed 7 years ago.
So for a rundown of my problem, I am working for a company that uses SQL and Visual Studio, and I am in training since I have never used SQL before. The way they said that they connect to the SQL server using ADO.Net, however as I have been researching, there are a lot of different ways to go about doing this.
My question is, in a Console Application, if I already have a connection string and I do not need to build one, how do I connect to SQL that doesn't use an Entity Frame work or uses LINQ to SQL?
This page shows a good example of how to go about it. Here's the piece of code that would be of most interest to you:
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//Use reader.GetInt32, reader.GetString, etc
//depending on the type of data in the table
Console.WriteLine("{0} {1} {2}", reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
}
}
How do I insert data into a .dbf format database using SQL in Visual c#?
Is it same as when using MS Access?
OleDbConnection dbConn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\wz\Desktop\UBS\onetimecapture\onetimecapture\onetimecapture\bin\Debug\;Extended Properties=dBase IV;");
try
{
// Open connection.
dbConn.Open();
//string queryCutting = "INSERT INTO cuttingstatus.dbf ([Status]) VALUES(adddate)";
string queryCutting = "INSERT INTO cuttingstatus.dbf VALUES(adddate)";
OleDbCommand command_cutting = new OleDbCommand(queryCutting, dbConn);
command_cutting.Parameters.AddWithValue("adddate", "123");
command_cutting.ExecuteNonQuery();
dbConn.Close();
}
catch
{
MessageBox.Show("Error", "SCADA system", MessageBoxButtons.OK);
}
but it return an error say that
The Microsoft Jet database engine could not find the object
'cuttings'.
Make sure the object exists and that you spell its name and the path name correctly.
The database is called cuttingstatus.dbf, and it consist of only a single column Status.
Thanks for the help =)
What is the name of the table in the cuttingstatus.dbf?
The statement should be something like:
INSERT INTO TABLE_NAME
VALUES(adddate)
as the value of the variable queryCutting.
When making an OleDbConnection to use Database files, you want your connection source to point to the logical PATH WHERE the table is... not the actual table.
Connection dbConn = new OleDbConnection(#"Data ource=C:\SomePath\WhereAreAllTables;Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=dBase IV;");
Then, your insert query does not reference the .dbf extension... it is implied by the connection. Also, even though it may be a single column, it would be better to explicitly show the column and values such as :
string queryCutting = "INSERT INTO cuttingstatus ( YourColumnName ) VALUES ( #adddate )";
Next... Is it really a DBase IV system? FoxPro table? Clipper? I would ensure proper provider. If the data is actually from Foxpro origin, I would go to Microsoft and download the Visual Foxpro OleDb provider.
One final thought... is that the error is referring to a truncated table name of up to 8 characters "cuttings" which implies old DOS 8.3 file naming convensions. Don't know if that is what you are also running into for your problem.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How can I perform queries on access using the C#? I want to create tables, and Insert/Select data from my access database.
You should check out all things you can do with OdbcConnection and OdbcCommand.
You can even steal the Connection String for your connection from:
Access 2007 Connection String Samples
...that should be enough to get you started.
Here's a tutorial to get you started.
http://www.csharphelp.com/2006/01/ms-access-application-with-c/
Depending on your version of Access, you may want to check out differenc connection strings as well.
http://connectionstrings.com
Here are 2 pretty good starting tutorials
Here is a good intro into what is actually going on.
Here has some pretty helpful example code.
Protip: Make sure you have the correct ODBC Drivers installed if they
are not already. I felt SOOOO stupid for not figuring that out from
the start lol ;p
As far as dealing with you db assuming your not creating a access db on the fly all you would have to do is create your db in access, save it, and add it as a data source to your application.See here
Example Insert:
var insertStatement = #"insert into familytree (firstname, lastname, city, Tel, Email) values (#firstname, #lastname, #city, #tel, #email); SELECT ##IDENTITY";
//Open your connection and command
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand cmd = new OleDbCommand(insertStatement, connection))
{
//set parameters and values
var identityQuery = #"SELECT ##IDENTITY";
var identity = -1;
cmd.Parameters.Add("#firstname", 'foo');
cmd.Parameters.Add("#lastname", 'foo');
cmd.Parameters.Add("#city", 'foo');
cmd.Parameters.Add("#tel", '6666666');
cmd.Parameters.Add("#email", 'foo#foo.com');
connection.Open();
try{
var numberOfRowsEffected = command.ExecuteNonQuery();
//we should have 1 row effected.
if(numberOfRowsEffected>0){
cmd.CommandText = identityQuery;
//get the identity
identity = (int)cmd.ExecuteScalar();
}
}catch(InvalidOperationException ex){
//log and throw:
//cant open connection or Cannot execute a command
//within a transaction context that differs from the
//context in which the connection was originally enliste
}
return identity;
}
Same thing applies if you were wanting to create a table. just write your create table statement. see here for example and execute. But as far as common approaches go you generally want to have you table structures already set up for most simple apps and let your Application handle inserts, updates, and possibly deletes. Not saying you shouldn't do it that way but I would consider KISS whenever possible.
Oh and here is an msdn ref to the OleDbCommand class if you were wondering else you can do. OleDbCommand