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
Related
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!
I am currently writing my first .Net & C# application with Visual Studio, and have a need to write generated values to MySQL from the application.
At present, I can write values fine - but I need to be able to check to see if a value exists and display that line if it does exist, otherwise insert new line to table. My connection string is defined at the top of the form.
I have the following defined already, and it writes to the database successfully if no duplicate values exist in the LicenseKey column. If a duplicate exists, it throws an unhandled exception.
private void SaveDetails()
{
// MySQL 'insert' command
string InsertNewLicense = "insert into BCOM.LicenseDetails(LicenseeName,ComputerName,ContactName,ContactEmail,LicenseKey,CreationDate) values('" +this.textBoxLicenseeName.Text+ "','" +this.textBoxComputerName.Text+ "','" +this.textBoxContactName.Text+ "','" +this.textBoxContactEmail.Text+ "','" +this.textBoxLicenseKey.Text+ "','" +this.textBoxCreationDate.Text+ "');";
//MySQL instance details
MySqlConnection InsertLicenseDetails = new MySqlConnection(LicenseDatabaseConnection);
//MySQL command execution
MySqlCommand InsertCommand = new MySqlCommand(InsertNewLicense, InsertLicenseDetails);
// Handles command outputs.
MySqlDataReader InsertReader;
//Opens connection to run query on database
InsertLicenseDetails.Open();
// Here our query will be executed and data saved into the database.
MessageBox.Show("License Details Saved. Please ensure you have emailed the license to the customer.");
while (InsertReader.Read())
{
}
InsertLicenseDetails.Close();
}
What I want to happen is for a check to be run on the LicenseKey column to see if the value exists, before different actions are taken.
If the value does not exist, I would like to insert the new line to the table (like my existing command does).
If, however, the value does exist, I would like to pop up a form showing the values from the line that the duplicate appears in as a form.
Where would I put in an event handler to read MySQLException values? What exception would I have to respond to for a duplicate value or no database response?
I agree with what the others have said in their comments, you could change the SQL Query to do the check instead of having 2.
IF(SELECT ... WHERE A = B)
RETURN THAT THE VALUE ALREADY EXISTS
ELSE
INSERT NEW VALUE
Also there was a good comment about SQL Injection and parameterized queries. The query string should look a bit more like
INSERT into BCOM.LicenseDetails(LicenseeName,ComputerName,ContactName,ContactEmail,LicenseKey,CreationDate) values(#LicenseeName, #ComputerName, #ContactName ...);
and your SqlCommand be parameterized
InsertCommand.Paramaters.AddWithValue("#LicenseeName", this.textBoxLicenseeName.Text);
InsertCommand.Paramaters.AddWithValue("#ComputerName", this.textBoxComputerName.Text);
...
That should be a good start to get you going.
After looking at the queries for a while I decided to try a different tack - instead of using a direct check if it's there, I opted to use a count(*) query. When I click the save button on the form, the buttonClick_event calls SaveDetails(), which runs the following:
private void SaveDetails()
{
string InsertNewLicense = "INSERT into BCOM.LicenseDetails(LicenseeName,ComputerName,ContactName,ContactEmail,LicenseKey,CreationDate) values(#LicenseeName, #ComputerName, #ContactName, #ContactEmail, #LicenseKey, #CreationDate)";
string LicenseExistence = "SELECT COUNT(*) FROM BCOM.LicenseDetails WHERE LicenseKey LIKE #LicenseKey";
MySqlConnection LicenseDetails = new MySqlConnection(LicenseDatabaseConnection);
MySqlCommand InsertCommand = new MySqlCommand(InsertNewLicense, LicenseDetails);
InsertCommand.Parameters.AddWithValue("#LicenseeName", this.textBoxLicenseeName.Text);
InsertCommand.Parameters.AddWithValue("#ComputerName", this.textBoxComputerName.Text);
InsertCommand.Parameters.AddWithValue("#ContactName", this.textBoxContactName.Text);
InsertCommand.Parameters.AddWithValue("#ContactEmail", this.textBoxContactEmail.Text);
InsertCommand.Parameters.AddWithValue("#LicenseKey", this.textBoxLicenseKey.Text);
InsertCommand.Parameters.AddWithValue("#CreationDate", this.textBoxCreationDate.Text);
MySqlCommand QueryCommand = new MySqlCommand(LicenseExistence, LicenseDetails);
QueryCommand.Parameters.AddWithValue("#LicenseKey", this.textBoxLicenseKey.Text);
MySqlDataReader InsertReader;
LicenseDetails.Open();
if ((int)(long)QueryCommand.ExecuteScalar() >0)
{
MessageBox.Show("This license already exists in the database.");
}
else
{
InsertReader = InsertCommand.ExecuteReader();
MessageBox.Show("License Details Saved. Please ensure you have emailed the license to the customer.");
while (InsertReader.Read())
{
}
}
LicenseDetails.Close();
So, if the query against the license keys returns with any results at all (more than 0 rows returned), a messagebox pops up showing that the key already exists. If the resultant number of rows is 0, the insert command gets run.
This was figured out with a look through MySQL command notes, testing with phpMyAdmin, matching against existing projects online, and support from the following:
The SELECT query was figured out with great support from #Seige.
The query was parameterized with help from Seige, following on from the advice of Sani Huttunen. Many thanks to them both.
Changing to the count method was done on the advice of a fellow coder in another community online - a good friend and brilliant coder.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm building a SQL query, trying to make it safer by using a parameterized query. I've got the below, does this look ok or is there anything I can/need to change?
// Connection to SQL
string connectionString = "Data Source= PC\\SQL;Initial Catalog= Catalog;Integrated Security=False; User ID=; Password=";
// SQL Insert Command - Must Use The Below For Commands!
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand Insert = new SqlCommand("INSERT INTO database (OS) VALUES (#ad)", connection);
Insert.Parameters.AddWithValue("#ad", adtb.text);
connection.Open();
Insert.ExecuteNonQuery();
connection.Close();
I've left out certain details (db name etc).
Any help or suggestions will be greatly appreciated!
You should do it like this:-
// Read this connection string from `Web.Config` file instead.
string connectionString = "Data Source= PC\\SQL;
Initial Catalog= Catalog;Integrated Security=False; User ID=; Password=";
Can be written as follows to avoid re-compiling every time you change the connection strings:-
string connectionString = ConfigurationManager.ConnectionString["YourKey"]
.ConnectionString;
Consider using using statement to dispose your valuable resources:
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand Insert = new SqlCommand("INSERT INTO database (OS)
VALUES (#ad)", connection))
{
Insert.Parameters.Add("#ad", SqlDbType.NVarchar,10).Value = adtb.text;
connection.Open();
Insert.ExecuteNonQuery();
}
Avoid using AddWithValue, Read this.
I strongly feel taking a risk to answer your question, but anyway..
First of all, database is a reserved keyword in T-SQL. You should use it with square brackets like [database]. But as a better way, don't. Change it to non-reserved word which is meaningful for your.
Second, use using statement to dispose your SqlConnection and SqlCommand instead of calling .Dispose() method manually..
Third, as a best practice, don't use AddWithValue method. It may generate unexpected results. Use .Add() method or it's overloads. Read: Can we stop using AddWithValue() already?
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO [database] (OS) VALUES (#ad)";
cmd.Parameters.Add("#ad", SqlDbType.NVarChar, 16).Value = adtb.text;
con.Open();
cmd.ExecuteNonQuery();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public static string cs = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+Application.StartupPath+"\\TestDB.mdf;Integrated Security=True;User Instance=True";
I have tried the above code for making the string global. The problem is that the data is saved until the application is open. As soon as I restart the application, the changes are not reflected in the database file. Also help me where to keep the database during deployment. I am using SqlServer 2008 and the database location is the Application folder
I have this code:
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True");
cn.Open ();
string ins = "insert into table1 values ('"+textBox1.Text+"')";
SqlCommand c = new SqlCommand(ins, cn );
c.ExecuteNonQuery();
string exts = "select * from table1 where kri='"+textBox1.Text+"'";
SqlDataAdapter adp = new SqlDataAdapter(exts,cnn);
DataTable dt = new DataTable();
adp.Fill(dt);
MessageBox.Show(dt.Rows[0][0].ToString());
cn.Close ();
The first issue here is that you kind of misunderstand a connection string. Think of a connection string like your address. It's not you, but it's where you reside. That connection string is just stating where the data you want to manipulate resides.
With that understanding we can answer the question about what to do in deployment pretty easily. During deployment you will load the database on to a real SQL Server. That SQL Server will reside somewhere, and thus be the address to that database. Therefore, when deployed, you'll change that connection string because the data you want to manipulate will reside somewhere else.
As far as persisting changes to the database. I guess that really depends on what framework you're using to make changes to the database. But let's just work out an example with the plain old ADO classes. Let's assume we have a table named tbl. And in that table there is an ID and a Name, and we want to UPDATE that name. So, we might do it like this:
using (SqlConnection c = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("UPDATE tbl SET Name = #Name WHERE ID = #ID"))
{
cmd.Parameters.AddWithValue("#Name", someName);
cmd.Parameters.AddWithValue("#ID", someId);
cmd.ExecuteNonQuery();
}
In this example, someName and someId may come from text boxes. They may be stored somewhere else. That's up to you on where to get those from. But that would persist the changes to the database.
Now let's work on housing that connection string. We definitely don't want that hard coded like that. The most common approach is to put it into the app.config/web.config file. So, let's do that. In the app.config/web.config file add a key to the <connectionStrings> section:
<configuration>
<connectionStrings>
<add name="Default"
connectionString="{Enter Connection String Here}"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Alright, now that we've done that, let's get that connection string from there instead. First add a reference to System.Configuration. Next, modify that line of code to be this:
public static string cs = ConfigurationManager.ConnectionStrings["Default"]
And so now, when you deploy this application, you just fix up the connection string during deployment.
Basically, I would like a brief explanation of how I can access a SQL database in C# code. I gather that a connection and a command is required, but what's going on? I guess what I'm asking is for someone to de-mystify the process a bit. Thanks.
For clarity, in my case I'm doing web apps, e-commerce stuff. It's all ASP.NET, C#, and SQL databases.
I'm going to go ahead and close this thread. It's a little to general and I am going to post some more pointed and tutorial-esque questions and answers on the subject.
MSDN has a pretty good writeup here:
http://msdn.microsoft.com/en-us/library/s7ee2dwt(VS.71).aspx
You should take a look at the data-reader for simple select-statements. Sample from the MSDN page:
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
It basicly first creates a SqlConnection object and then creates the SqlCommand-object that holds the actual select you are going to do, and a reference to the connection we just created. Then it opens the connection and on the next line, executes your statements and returns a SqlDataReader object.
In the while-loop it then outputs the values from the first row in the reader. Every time "reader.Read()" is called the reader will contain a new row.
Then the reader is then closed, and because we are exiting the "using"-secret, the connection is also closed.
EDIT: If you are looking for info on selecting/updating data in ASP.NET, 4GuysFromRolla has a very nice Multipart Series on ASP.NET 2.0's Data Source Controls
EDIT2: As others have pointed out, if you are using a newer version of .NET i would recommend looking into LINQ. An introduction, samples and writeup can be found on this MSDN page.
The old ADO.Net (sqlConnection, etc.) is a dinosaur with the advent of LINQ. LINQ requires .Net 3.5, but is backwards compatible with all .Net 2.0+ and Visual Studio 2005, etc.
To start with linq is ridiculously easy.
Add a new item to your project, a linq-to-sql file, this will be placed in your App_Code folder (for this example, we'll call it example.dbml)
from your server explorer, drag a table from your database into the dbml (the table will be named items in this example)
save the dbml file
You now have built a few classes. You built the exampleDataContext class, which is your linq initializer, and you built the item class which is a class for objects in the items table. This is all done automatically and you don't need to worry about it. Now say I want to get record with the itemID of 3, this is all I need to do:
exampleDataContext db = new exampleDataContext(); // initializes your linq-to-sql
item item_I_want = (from i in db.items where i.itemID == 3 select i).First(); // using the 'item' class your dbml made
And that's all it takes. Now you have a new item named item_I_want... now, if you want some information from the item you just call it like this:
int intID = item_I_want.itemID;
string itemName = item_I_want.name;
Linq is very simple to use! And this is just the tip of the iceberg.
No need to learn antiquated ADO when you have a more powerful, easier tool at your disposal :)
Reads like a beginner question. That calls for beginner video demos.
http://www.asp.net/learn/data-videos/
They are ASP.NET focused, but pay attention to the database aspects.
topics to look at:
ADO.NET basics
LINQ to SQL
Managed database providers
If it is a web application here are some good resources for getting started with data access in .NET:
http://weblogs.asp.net/scottgu/archive/2007/04/14/working-with-data-in-asp-net-2-0.aspx
To connect/perform operations on an SQL server db:
using System.Data;
using System.Data.SqlClient;
string connString = "Data Source=...";
SqlConnection conn = new SqlConnection(connString); // you can also use ConnectionStringBuilder
connection.Open();
string sql = "..."; // your SQL query
SqlCommand command = new SqlCommand(sql, conn);
// if you're interested in reading from a database use one of the following methods
// method 1
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
object someValue = reader.GetValue(0); // GetValue takes one parameter -- the column index
}
// make sure you close the reader when you're done
reader.Close();
// method 2
DataTable table;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
// then work with the table as you would normally
// when you're done
connection.Close();
Most other database servers like MySQL and PostgreSQL have similar interfaces for connection and manipulation.
If what you are looking for is an easy to follow tutorial, then you should head over to the www.ASP.net website.
Here is a link to the starter video page: http://www.asp.net/learn/videos/video-49.aspx
Here is the video if you want to download it: video download
and here is a link to the C# project from the video: download project
Good luck.
I would also recommend using DataSets. They are really easy to use, just few mouse clicks, without writing any code and good enough for small apps.
If you have Visual Studio 2008 I would recommend skipping ADO.NET and leaping right in to LINQ to SQL
#J D OConal is basically right, but you need to make sure that you dispose of your connections:
string connString = "Data Source=...";
string sql = "..."; // your SQL query
//this using block
using( SqlConnection conn = new SqlConnection(connString) )
using( SqlCommand command = new SqlCommand(sql, conn) )
{
connection.Open();
// if you're interested in reading from a database use one of the following methods
// method 1
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
object someValue = reader.GetValue(0); // GetValue takes one parameter -- the column index
}
// make sure you close the reader when you're done
reader.Close();
// method 2
DataTable table;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
// then work with the table as you would normally
// when you're done
connection.Close();
}