i found using of prepared statements in PHP by mysqli_stmt_prepare() Function.
what is like it in C# for SQL-Server?
i found this code example(using parameterize command). is this what i am looking for?
SqlConnection conn = new SqlConnection();
SqlCommand com = new SqlCommand();
SqlDataAdapter dap = new SqlDataAdapter();
DataTable tbl = new DataTable();
SqlParameter param = new SqlParameter();
conn.ConnectionString = #"Data Source=...";
com.Connection = conn;
com.CommandText = "select * from tbl1 where id<#id";
com.Parameters.AddWithValue("#id",4);
com.CommandType = CommandType.Text;
dap.SelectCommand = com;
conn.Open();
dap.Fill(tbl);
conn.Close();
dataGridView1.DataSource = tbl;
if NO, then what?
if YES, tell me how to using character '?' instead of writing #id in command text.
thanks
SQL Server (at least, via SqlClient) uses named parameters. That code will indeed execute a parameterised query, but a few notes:
it hasn't been formally "prepared" (see .Prepare()), but you pretty much never need to anyway
several of those objects are IDisposable; you should have usings for them
DataTable (and adapter, etc) will work, but is in decline (with mapped classes being preferred, IMO)
seeing a DataGridView and a SqlCommand in the same method probably means your UI code is too close to the data access code; I would push the data-access stuff down a level, personally
For example:
DataTable tbl = new DataTable();
using(var conn = new SqlConnection(#"Data Source=..."))
using(var com = conn.CreateCommand())
{
com.CommandText = "select * from tbl1 where id<#id";
com.Parameters.AddWithValue("#id",4);
com.CommandType = CommandType.Text;
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = com;
conn.Open();
dap.Fill(tbl);
conn.Close();
}
return tbl;
(and bind it to the DataGridView back at the UI)
Of course, if the parameter value is always 4 you could code that into the TSQL directly.
Yes, but it is no way to use '?' mark.
Related
I have an SQL select query that will return multiple values, but I cannot find a way to store/access them. I am using Visual Studio 2015 and an Access database.
Below is my most recent attempt using a data table/grid view.
string now = DateTime.Today.ToString("dd/MM/yyyy");
//Establish and open new database connection.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase32BITConnectionString"].ToString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmd.CommandText = String.Format ("select Rating from [RATINGS] where Today_Date like #now and Name like #name");
cmd.Parameters.AddWithValue("#now", now);
cmd.Parameters.AddWithValue("#name", name);
cmd.Connection = con;
adapter.SelectCommand = cmd;
adapter.Fill(dt);
con.Close();
testGridView.DataSource = dt;
name is a variable passed into the method. I don't necessarily need it stored in a data table, i just need to be able to access the results individually to average them (array?).
Any advice would be much appreciated
I'm using a C# SqlDataReader in many loops. Unfortunately I can't read the whole table and store the data in a list. So I have to create a SqlDataReader again and again. Once the SqlDataReader is created, its very fast. But the creation of the SqlDataReader via ExecuteReader takes too much time.
Is there any possibility to improve the creation time of the SqlDataReader?
I'm using .NET 4.5.1 and SQL Server 2008.
string sql = "select CURRENT_TIMESTAMP";
var connection = Connections.Get();
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.CommandTimeout = 0;
var reader = sqlCommand.ExecuteReader(CommandBehavior.Default);
Thanks
Michael
string conString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
SqlConnection conn = new SqlConnection(conString);
conn.Open();
SqlCommand cmd = new SqlCommand("select TOP 50000 * from users", conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
please use DataTable and SqlDataAdapter to read the data
Instead of using ExecuteReader
The database that I am connecting to has a table with a Full Text Search index. This works correctly.
select * from MyTable where contains(*, 'value')
In WPF if I send that exact command down it works. However value is not hard coded it is something an user types in so it needs to be protected for SQL injection. The issue is that in doing so it does not return results. Here is my code;
DataTable dt = new DataTable();
string ConString = "Data Source=127.0.0.1,1433;Initial Catalog=MyDB;User Id=sa;Password=amazingSecurePassword;";
using (SqlConnection con = new SqlConnection(ConString))
{
string sqlCMD = "select * from MyTable where contains(*, #s1)"
SqlCommand cmd = new SqlCommand(sqlCMD, con);
SqlDataAdapter da = new SqlDataAdapter();
try
{
con.Open();
cmd = new SqlCommand(sqlCMD, con);
cmd.Parameters.Add(new SqlParameter("#s1", "value"));
da.SelectCommand = cmd;
da.Fill(dt);
con.Close();
}
catch (Exception x)
{
//Error logic
}
finally
{
cmd.Dispose();
con.Close();
}
}
Edit: #Mike comment worked. Change the SqlDbType.NVarChar fixed the issue
As noted in the above comment, setting the SQlDbType to NVarChar during the creation of the SqlParameter helps the CLR determine the right data type. More info about the SqlParameter constructor at MSDN.
How use WHERE in SqlDataAdapter in C#?
I want get name in a textbox and use that at query but it wont work .
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
string _search_name = txt_search.Text;
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=_search_name ", sqlconnection);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
Prepare the command text and use a parameter for the value of your search.
Then use that command text to initialize a new SqlCommand. Fill the parameter value with AddWithValue and pass the SqlCommand to the constructor of the SqlDataAdapter.
string cmdText = "SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 " +
"FROM tbl_user WHERE dbo.tbl_user.name=#search_name"
SqlCommand cmd = new SqlCommand(cmdText, sqlconnection);
cmd.Parameters.AddWithValue("#search_name", _search_name);
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
The SqlDataAdapter will store your command as the SelectCommand property and will use the passed in SqlCommand to execute the query to retrieve the records from the database.
Keep in mind that AddWithValue is a shortcut with some drawbacks. For example it pass Always a string as a nvarchar parameter with size equal to the actual lenght of the variable. This effectively reduces the performance of the Sql Server Optimizer.
This is a very enlightening article on the issue
So, you were pretty close, you just needed to define a parameter inside the query and then add that parameter. However, in the following code block I've also conveniently recommended a more appropriate approach to using the classes needed to get the data (pun intended). The using statement here ensures that the objects get disposed of properly after you are done using them (man I just can't stop with the puns!)
using (SqlConnection c = new SqlConnection(connString))
{
c.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(
"SELECT dbo.tbl_user.field1, dbo.tbl_user.field2 FROM tbl_user " +
"WHERE dbo.tbl_user.name= #name", c))
{
sda.SelectCommand.Parameters.AddWithValue("#name", txt_search.Text);
DataTable dt = new DataTable();
sda.Fill(dt);
}
}
Try this.
you were using the string directly in the query which will go undetected.
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;
Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=#searchName" , sqlconnection);
SDA.SelectCommand.Parameters.AddWithValue("#searchName", txt_search.Text);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
my problem is that , i made a child form for searching , but i have problem in sql query and parameters , my code is
SqlConnection sc = new SqlConnection(
"Data Source=MOHAMMED-PC;Initial Catalog=salessystem;Integrated Security=True");
SqlCommand command = new SqlCommand(
"Select * from customers WHERE (docno = #doc) OR (NAME LIKE #name ) OR (salepoint = #salepoint)", sc);
DataTable dt = new DataTable();
command.Parameters.AddWithValue("#doc", doctxt.Text);
command.Parameters.Addwithvalue("#name", nametxt.Text);
command.Parameters.AddWithValue("#salepoint", salepointtxt.Text);
SqlDataAdapter sda = new SqlDataAdapter(command, sc);
sda.Fill(dt);
dataGridView1.DataSource = dt;
i have error in sql adapter command and in where clause command , any help ??
Three things:
You have a typo on this line
command.Parameters.Addwithvalue("#name", nametxt.Text);
The method is AddWithValue (note the case difference)
The constructor of SqlDataAdapter takes the command but no connection then since the command already contains the connection, so this is correct:
SqlDataAdapter sda = new SqlDataAdapter(command);
Probably the most important last:
If you use LIKE you need to use the wild-cards %:
command.Parameters.AddWithValue("#name", string.Format("%{0}%",nametxt.Text);