It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I am new Programmer. In my Comp. I am the Only Programmer. So I have many Questions in my Mind.
In my Project i am using Below Code For add.
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select * from " + datatable + " where code='" + textBox1.Text + "'";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
already = 1;
}
connection.Close();
Is this Correct Way. Or DAL, Stored Procedure, 3 tire Architure Which is most effective. And What standard Code is maintain in Companies.
I am doing Project and Got Solutions Also. But I don't know this way is Correct or Not.
I think Most of you understand my problem?.
Thanks in Advance....
How you divide your code into layers is more a matter of taste than an absolute must. You get some advantages by at least separating the database code from the user interface. You would for example easily notice the problem with using the text from a textbox directly in a database query if the database code was separated from the UI.
There are some serious problems with your code:
You are not disposing all disposable objects, which wastes resources, and might cause errors in the long run.
The code is wide open for SQL injections, you should use parameterised queries.
Also:
You are fetching all the data in the table, when you only need to know if there is any data or not.
Never use select *, only fetch the fields that you are going to use.
Disposing connections and readers aldo close them, so if you use using blocks to dispose the objects, you don't have to close them first:
using (MySqlConnection connection = new MySqlConnection(MyConString)) {
using (MySqlCommand command = connection.CreateCommand()) {
command.CommandText = "select count(*) from " + datatable + " where code = #Code";
command.Parameters.Add("#Code", dbType.VarChar, 50).Value = textBox1.Text;
connection.Open();
if ((int)(command.ExecuteScalar()) > 0) {
already = 1;
}
}
}
Keep your connection string at global scope, so if it changes you don't have to re-write it again in each method interacts with the database.
Your command is varnuable to SQL injection attack, you should change that to something like:
command.CommandText = "select * from #datatable where code=#code";
command.Parameters.Add(new SqlParameter("datatable", datatable));
command.Parameters.Add(new SqlParameter("code", textBox1.Text));
Use using or try/finally to close your connection whenever you done from it and also do that for the datareader, so:
using (MySqlConnection connection = new MySqlConnection(MyConString))
{
//use the connection here
}
In general use the using statement with all object that implements IDisposable interface, so they will be disposed probably. when you use try/finally or using you are sure that even if something getting wrong, like exception has been thrown your object is disposed.
You should keep your database logic separated from the UI. check the pattern of 3 tier architecturee.
To ensure that connections are always closed, open the connection inside of a using block. as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
This is a part of Connection Pooling. And it is one of the good way of doing Sql connection.
Related
I have a stored procedure that I need to run in C# and set the result set returning from the SP in a HTML table. Please note that the SP is working well in SSMS and returning results.
The c# code I am using is (it is in an ASP 4.5 project):
SQLDatabase sqldb = new SQLDatabase();
using (SqlConnection sqlcn = new SqlConnection(sqldb.GetConnectionString().ToString()))
{
if (sqlcn.State == ConnectionState.Closed)
{
sqlcn.Open();
}
SqlCommand cmd = new SqlCommand("[MyStoredProcedure]", sqlcn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FromDate", Convert.ToDateTime(txtFrom.Value.ToString()));
cmd.Parameters.AddWithValue("#ToDate", Convert.ToDateTime(txtTo.Value.ToString()));
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
a.Fill(ds);
dtExtra = ds.Tables[0];
}
}
This code above is returning 0 rows, even though the SP is working in SSMS. While debugging, the connectionstring and the parameters are coming all true, no issue. The connectionstring is:
<add name="DefaultDB" connectionString="Data Source=TestEnv;Initial Catalog=TestTable;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
I don't understand what may cause this. I found the topic below, but I am using Integrated Security=SSPI in my connection string already, so it did not help me. Any advice would be appreciated.
ASP.NET stored proc call bringing back no rows, but does in Management Studio!
EDIT: SOLVED! Thanks #NineBerry. It turned into a between/and usage problem in SP. Changing txtTo.Value as: DateTime.Today.AddDays(1).ToString("yyyy-MM-dd"); in the code fixed the issue (It was DateTime.Today.ToString("yyyy-MM-dd") before, I should have included it in the code part, didn't think it is related to that, sorry). Better solution would be updating the SP using >= and <= instead of between/and keywords tho.
I would modify your code to simply be:
using(var dbConnection = new SqlConnection("..."))
using(var command = new SqlCommand(query, dbConnection))
{
dbConnection.Open();
...
}
Handling the connection pooling in the using block is always a good idea per Microsoft guideline:
To ensure that connections are always closed, open the connection
inside of a using block, as shown in the following code fragment.
Doing so ensures that the connection is automatically closed when the
code exits the block.
You are checking if the connection is closed, what if the connection is idle? By using the using syntax you implement dispose. So it will correctly close your connection, so you should not need to check if the connection is closed unless you are using a singleton for the connection.
After reading your question, you may have more than just the one issue I pointed out. I would recommend a service account with access the specific data you are seeking, that the application can access rather than integrated security.
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();
}
This question already has answers here:
Do I have to Close() a SQLConnection before it gets disposed?
(8 answers)
Closed 9 years ago.
When using a using block for SQL connections in C#, does this also a close method? I'm asking as I need to explicitly use the con.Open() method. I found this example:
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open(); // open method
string queryString = "select * from db";
SqlCommand cmd = new SqlCommand(queryString, con);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
??? // What about a close method?
}
Or does the using block close the connection itself?
using translates to:
SqlConnection con = new SqlConnection(connectionString)
try
{
con.Open(); <-- open method
string queryString = "select * from db";
SqlCommand cmd = new SqlCommand(queryString, con);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
}
finally
{
if (con!= null)
((IDisposable)con).Dispose();
}
where ((IDisposable)con.Dispose(); closes what is to be closed.
You don't have to close it - using is enough. MSDN says:
To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
No, you don't have to call the Close-Method of the SqlConnection.
When it gets disposed on the end of the using, it closes automatically.
(The Dispose-Method calls Close()) [1]
The other answers are correct, however, I want to be a bit more explicit.
The MSDN states the following:
Close and Dispose are functionally equivalent.
Because using using will call Dispose a separate call to Close is not needed.
when you use the 'using' keyword and create a connection in it .
the connection is open as far as there is the scope of the 'using' keyword when closing bracket is reached the connection is closed automatically as it was defined within a scope and the scope is not in exist
in other words treat it as the local variable which can be accessed within the scope only.
hope this will help.
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
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();
}