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();
}
Related
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.
I am getting an error while connecting to the sql from my cs file. I am trying to create CLR functions in c# without using any IDE which is the requirement. I need to access the database to get some value. Following is the code to connect to my database in c#.
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT COUNT(*) AS 'Order Count' FROM customer_master with (nolock)", conn);
SqlContext.Pipe.ExecuteAndSend(cmd);
return (int)cmd.ExecuteScalar();
}
but I am getting the following error:
"The requested operation requires a SqlClr context, which is only available when running in the Sql Server process". If i use pipe i don't know how to convert that to an int value. Any suggestions please....
As per this Blog post, try it like this, with the SQLConnection not in a using. The SQLCommand is Disposable and should be in a using though.
SqlConnection conn = new SqlConnection("context connection=true") ;
using(SqlCommand cmd = new SqlCommand(
"SELECT COUNT(*) AS 'Order Count' FROM customer_master with (nolock)", conn))
{
conn.Open();
return (int)cmd.ExecuteScalar();
}
I wrote the below first, but I think the above is the answer, I'm leaving struck out in case it is relevant.
A ContextConnection is a connection back down the existing open connection that the SQL calling the CLR function is using.
To use a SQL CLR Function with a ContextConnection you have to call it from inside a SQL Statement.
e.g. (where CLRConvert is my CLR function that connects back to my database and performs a query and converts stuff).
select dbo.CLRConvert(Data) from MyTables;
If you need to call it outside of here, you will need a proper connection string.
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.
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
I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace.
I'm using SqlConnection for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google.
using (var conn = new SqlConnection(yourConnectionString))
{
var cmd = new SqlCommand("insert into Foo values (#bar)", conn);
cmd.Parameters.AddWithValue("#bar", 17);
conn.Open();
cmd.ExecuteNonQuery();
}
Since you seem to be just getting started with this now is the best time to familiarize yourself with the concept of a Data Access Layer (obligatory wikipedia link). It will be very helpful for you down the road when you're apps have more interaction with the database throughout and you want to minimize code duplication. Also makes for more consistent behavior, making testing and tons of other things easier.
using (SqlConnection myConnection new SqlConnection("Your connection string"))
{
SqlCommand myCommand = new SqlCommand("INSERT INTO ... VALUES ...", myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
}