I tried to adapt the solution from Understanding of nested SQL in C# Reply 4.
But it dont work. I cant find the mistake. Think it is something that the statement cant use a parameter as part of the table name.
string srcqry = #"USE [" + TableName+ "] " +
#"select TABLE_NAME from [INFORMATION_SCHEMA].[TABLES]";
using (SqlConnection srccon = new SqlConnection(cs))
using (SqlCommand srccmd = new SqlCommand(srcqry, srccon))
{
srccon.Open();
using (SqlDataReader src = srccmd.ExecuteReader())
{
string insqry = #"USE [" + TableName+ "] " + "ALTER SCHEMA "+SchemaNameNew+" TRANSFER [dbo].#tabelle";
// create new connection and command for insert:
using (SqlConnection inscon = new SqlConnection(cs))
using (SqlCommand inscmd = new SqlCommand(insqry, inscon))
{
inscmd.Parameters.Add("#tabelle", SqlDbType.NVarChar, 80);
inscon.Open();
while (src.Read())
{
inscmd.Parameters["#tabelle"].Value = src["TABLE_NAME"];
inscmd.ExecuteNonQuery();
}
}
}
}
I got the error that the statement is wrong in the #tabelle area.
Any idea why it wont work?
Thanks
I found a working solution.
while (src.Read())
{
var table= src["TABLE_NAME"];
var con = new System.Data.SqlClient.SqlConnection(cs);
con.Open();
var cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"USE [" + dbname+ "] " + "ALTER SCHEMA " + schemaname+ " TRANSFER [dbo]."+table;
cmd.ExecuteNonQuery();
con.Close();
}
Related
I have a table TümEnvanter$ which has 2 columns equipment code (Ekipman) and their description (Tanım).
User chooses the equipment from the combo box, and I want the description of the chosen equipment to appear in the label at the time they choose from combobox.
Here is what I tried:
SqlCommand cmdTanim = new SqlCommand("select Tanım from TümEnvanter$ where Ekipman = '" + comboBox_ekipman.Text + "'", connect);
connect.Open();
SqlDataReader reader = cmdTanim.ExecuteReader();
string tanim = reader.ToString();
labelTanim.Text = "Ekipman Tanımı: "+tanim+" ";
When I use this code, I get in the label:
Ekipman Tanımı: System.Data.SqlClient.SqlDataReader
How can I fix this? Thank you.
If you only expect a single value, then ExecuteScalar is much simpler than using a reader, i.e.
labelTanim.Text = Convert.ToString(cmdTanim.ExecuteScalar());
In general, perhaps consider tools like "Dapper" which would make this simple even in multi-row cases and solve the SQL injection problem trivially:
string s = connect.QuerySingle<string>(
"select Tanım from TümEnvanter$ where Ekipman = #val", // command
new { val = comboBox_ekipman.Text }); // parameters
You should try this code, it gathers some good practices, such as:
1) Uses using statement to release unamnaged resources (SQL connections, IDisposables in general).
2) Prevents from SQL injection using Parameters field of SqlCommand object.
Also, I used ExecuteScalar method, mentioned by #MarcGravell, which simplifies the code.
public void SqlConn()
{
string tanim = null;
using (SqlConnection connect = new SqlConnection("connectionString"))
{
using (SqlCommand cmdTanim = new SqlCommand())
{
cmdTanim.Connection = connect;
cmdTanim.CommandText = "select Tanım from TümEnvanter$ where Ekipman = #param";
cmdTanim.Parameters.Add("#param", SqlDbType.VarChar).Value = comboBox_ekipman.Text;
connect.Open();
tanim = (string)cmdTanim.ExecuteScalar();
}
}
labelTanim.Text = "Ekipman Tanımı: " + tanim + " ";
}
Something like this:
// wrap IDisposable into using
using (SqlConnection connect = new SqlConnection("Put_Connection_String_Here"))
{
connect.Open();
// Make SQL readable and parametrized
string sql =
#"select Tanım
from TümEnvanter$
where Ekipman = #prm_Ekipman";
// wrap IDisposable into using
using (SqlCommand cmdTanim = new SqlCommand(sql, connect))
{
//TODO: explicit typing Add(..., DbType...) is a better choice then AddWithValue
cmdTanim.Parameters.AddWithValue("#prm_Ekipman", comboBox_ekipman.Text);
// We want one record only; ExecuteScalar() instead of ExecuteReader()
// String interpolation shortens the code
labelTanim.Text = $"Ekipman Tanımı: {cmdTanim.ExecuteScalar()} ";
}
}
Use this code instead by using the reader() method of SqlDataReader to read and access the contents of the SqlDataReader.
SqlCommand cmdTanim = new SqlCommand("select Tanım from TümEnvanter$ where Ekipman = '" + comboBox_ekipman.Text + "'", connect);
connect.Open();
SqlDataReader reader = cmdTanim.ExecuteReader();
if(reader.HasRows){
reader.read();
string tanim = reader.ToString();
labelTanim.Text = "Ekipman Tanımı: "+tanim+" ";
}
Hope this code snippet works for you.
Use below code :
SqlCommand cmdTanim = new SqlCommand("select Tanım from TümEnvanter$ where Ekipman = '" + comboBox_ekipman.Text + "'", connect);
connect.Open();
SqlDataReader reader = cmdTanim.ExecuteReader();
string tanim = string.Empty;
while (reader.Read())
{
tanim= reader["Tanım"].ToString()
}
labelTanim.Text = "Ekipman Tanımı: "+tanim+" ";
public void buttonclick(object sender,eventArgs e)
{
SqlConnection con0 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con0.Open();
SqlCommand cmd0 = new SqlCommand("", con0);
con0.Close();
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con1.Open();
SqlCommand cmd3 = new SqlCommand("book_master_insert", con1);
cmd3.CommandType = CommandType.StoredProcedure;
SqlParameter customer_id = new SqlParameter("#customer_id", cust_id);
SqlParameter booking_from = new SqlParameter("#booking_from", ddlfrom.SelectedItem.Text);
SqlParameter booking_destination = new SqlParameter("#booking_destination", ddlto.SelectedItem.Text);
SqlParameter load_type = new SqlParameter("#load_type", ddlLoadtype.SelectedItem.Text);
SqlParameter no_of_containers = new SqlParameter("#no_of_containers", txt_no_of_container.Text);
SqlParameter booking_pickupdate = new SqlParameter("#booking_pickupdate", txt_date.Text);
SqlParameter booking_pickuptime = new SqlParameter("#booking_pickuptime", txt_time.Text);
SqlParameter booking_createdate = new SqlParameter("#booking_createdate", localDate);
cmd3.Parameters.Add(customer_id);
cmd3.Parameters.Add(booking_createdate);
cmd3.Parameters.Add(booking_from);
cmd3.Parameters.Add(booking_destination);
cmd3.Parameters.Add(load_type);
cmd3.Parameters.Add(no_of_containers);
cmd3.Parameters.Add(booking_pickupdate);
cmd3.Parameters.Add(booking_pickuptime);
cmd3.ExecuteNonQuery();
con1.Close();
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con2.Open();
SqlCommand cmd2 = new SqlCommand("select booking_ID from booking_master where customer_id='"+cust_id+"' and booking_from='" + ddlfrom.SelectedItem.Text + "'and booking_destination='" + ddlto.SelectedItem.Text + "' and load_type='" + ddlLoadtype.SelectedValue + "' and no_of_containers='" + txt_no_of_container.Text + "' and CAST (booking_pickupdate as date) ='" + txt_date.Text + "' and booking_pickuptime='" + txt_time.Text + "';", con2);
SqlDataReader rdr = cmd2.ExecuteReader();
while (rdr.Read())
{
booking_ID = rdr["booking_ID"].ToString();
}
con2.Close();
}
Because con0, con1, and con2 are the same, you can write it like this, and please make cmd2 like cmd3, using parameterized query:
using (var conn = new SqlConnection("...Connection String..."))
{
conn.Open();
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
// Query1
cmd.CommandText = "...Query1...";
cmd.ExecuteNonQuery();
// Query2
cmd.CommandText = "...Query2...";
cmd.ExecuteReader();
}
}
Talking about efficiency first what are you trying to do?
System.Data.SqlClient ( ADO.Net ) re-use connection pooling if it detects new connection is same with the first connection made base on it connectionstring.
Calling multiple SqlConnection doesn't matter as long as you close and dispose it after use. Much better if you wrap it with using() {} statement, but keep in mind that it depend on what you are trying to do or what you requirement is. Open/Close of connection is much cheaper than hold open connection for long time. If you can re-use connection do it like what #x... answers.
It is nothing to do with efficiency but you should AVOID appending user input value in you SQL query. This lead to SQL injection and exploitation like what #mar_s said. Alternatively you can use cmd.Parameters.AddWithValue("#Name", "Bob"); for your safety.
Note : I haven't tested the code :
public void buttonclick(object sender,eventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["BUM"].ConnectionString;
using(SqlConnection con0 = new SqlConnection(connectionString))
{
con0.Open();
using(SqlCommand cmd = new SqlCommand("book_master_insert", con0))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#customer_id", cust_id);
cmd.Parameters.AddWithValue("#booking_from", ddlfrom.SelectedItem.Text);
cmd.Parameters.AddWithValue("#booking_destination", ddlto.SelectedItem.Text);
cmd.Parameters.AddWithValue("#load_type", ddlLoadtype.SelectedItem.Text);
cmd.Parameters.AddWithValue("#no_of_containers", txt_no_of_container.Text);
cmd.Parameters.AddWithValue("#booking_pickupdate", txt_date.Text);
cmd.Parameters.AddWithValue("#booking_pickuptime", txt_time.Text);
cmd.Parameters.AddWithValue("#booking_createdate", localDate);
cmd.ExecuteNonQuery();
// This is a BAD idea and you should replace this using parametrized queries
using(SqlCommand cmd2 = new SqlCommand("select booking_ID from booking_master where customer_id='"+cust_id+"' and booking_from='" + ddlfrom.SelectedItem.Text + "'and booking_destination='" + ddlto.SelectedItem.Text + "' and load_type='" + ddlLoadtype.SelectedValue + "' and no_of_containers='" + txt_no_of_container.Text + "' and CAST (booking_pickupdate as date) ='" + txt_date.Text + "' and booking_pickuptime='" + txt_time.Text + "';", con2))
{
using(SqlDataReader rdr = cmd2.ExecuteReader())
{
while (rdr.Read())
{
booking_ID = rdr["booking_ID"].ToString();
}
}
}
}
}
}
I'm having trouble with a SQL query:
using (SqlConnection conn = new SqlConnection("user id=user;" + "password=pass;" + "server=server;" + "database=db;"))
{
using (SqlCommand comm = new SqlCommand(#"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'"))
{
conn.Open();
comm.Connection = conn;
MessageBox.Show("TEST: {0}", Convert.ToString((int)comm.ExecuteScalar()));
}
}
I'm expecting to get an int in the message box conveying the number of rows that BolagsID occurs in. But I get 0 every time. I've tried the query in SQL Server Management Studio and it works fine there. What am I doing wrong/missing?
EDIT:
This works, but now I don't know how to parameterize the values:
string query = #"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = " + BolagsID;
ADODB.Connection conn2 = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset();
string strConn = "Provider=...;Data Source=...;Database=...;User Id=...;Password=...";
conn2.Open(strConn);
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic;
rs.Open(query, conn2);
if (rs.Fields[0].Value > 0)
...stuff...
Like others are saying, parameters are a good idea. Here's something to get you started:
string query = #"SELECT Count(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = #BolagsID";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#BolagsID", SqlDbType.NVarChar).Value = BolagsID;
conn.Open();
MessageBox.Show("TEST: {0}", Convert.ToString((int)cmd.ExecuteScalar()));
conn.Close();
}
Basically a 0 is returned if there is an error in your query, so even though SSMS is smart enough to resolve it, the sql command isn't.
A quick way to make sure that everything else is working okay is to change the query to just "SELECT Count(*) FROM [CompaniesDB].[dbo].[Companies]". If that doesn't work then the issue could lie with your database connection (permissions?) or something else.
Try assigning SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'" to a string str as follows
string str =#"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'";
using (SqlConnection conn = new SqlConnection("user id=user;" + "password=pass;" + "server=server;" + "database=db;"))
{
using (SqlCommand comm = new SqlCommand(str))
{
conn.Open();
comm.Connection = conn;
MessageBox.Show("TEST: {0}", Convert.ToString((int)comm.ExecuteScalar()));
}
}
Then do a watch/quickwatch on str's value to get the exact query that is getting run and then run the same query in Sql Managment studio. If you get 0 in Sql Management Studio as well, then the problem is that the data is just not there.
I tried a lot of stuff before trying out a whole different approach. This gives me the result I want:
string query = #"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = " + BolagsID;
ADODB.Connection conn2 = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset();
string strConn = "Provider=...;Data Source=...;Database=...;User Id=...;Password=...";
conn2.Open(strConn);
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic;
rs.Open(query, conn2);
if (rs.Fields[0].Value > 0)
...stuff...
Note that both connection and record set are closed outside of this code snippet.
I am trying to write to a database from c#:
using (SqlConnection connection = new SqlConnection())
{
try
{
connection.ConnectionString = "Data Source=nesoi;Initial Catalog=SalesDWH;Integrated Security=True";
// This creates an object with which you can execute sql
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = #"INSERT INTO [SalesDWH].[dbo].[PendingSpecimens]
([Date Entered]
,[Specimen ID]
,[Test]
,[Agency])
VALUES (#DateEntered,#SpecimenID,#Test,#Agency)";
command.CommandType = CommandType.Text;
// This is how you add a parameter to your sql command
// This way you are protected against SQL injection attacks
SqlParameter DateEntered = command.CreateParameter();
DateEntered.ParameterName = "#DateEntered";
DateEntered.Value = fields[0];
command.Parameters.Add(DateEntered);
SqlParameter SpecimenID = command.CreateParameter();
SpecimenID.ParameterName = "#SpecimenID";
SpecimenID.Value = fields[1];
command.Parameters.Add(SpecimenID);
SqlParameter Test = command.CreateParameter();
Test.ParameterName = "#Test";
Test.Value = fields[2];
command.Parameters.Add(Test);
SqlParameter Agency = command.CreateParameter();
Agency.ParameterName = "#Agency";
Agency.Value = fields[4];
command.Parameters.Add(Agency);
connection.Open();
int someint=command.ExecuteNonQuery();
}
}
catch(Exception ee)
{
textBox1.Text = ee.ToString();
}
In addition to no errors being returned, it has not written anything either!
What am I doing wrong?
I suspect that this line:
command.ExecuteNonQuery();
is not working.
Mut I do not understand why
please help!
Try this:
using (SqlConnection connection = new SqlConnection("Data Source=nesoi;Initial Catalog=SalesDWH;Integrated Security=True"))
{
string queryString = "INSERT INTO SalesDWH.dbo.PendingSpecimens([Date Entered], [Specimen ID], Test, Agency) VALUES (" + fields[0] + ", " + fields[1] + ", " + fields[2] + ", " + fields[4] + ")";
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
Maybe you are missing the parentheses in the values clause?
Iam fairly new to SQLClient and all, and iam having a problem with my SQL tables..when ever i run my code, the data, rather than getting updated, attaches itself to the already existing records in the tables..here's my code
SqlConnection conneciones = new SqlConnection(connectionString);
SqlCommand cmd;
conneciones.Open();
//put values into SQL DATABASE Table 1
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
cmd = new SqlCommand("insert into URL_Entries values('" + CleanedURLlist[ok] + "' , '" + DateTime.Now + "' , '" + leak + "' )", conneciones);
cmd.ExecuteNonQuery();
}
conneciones.Dispose();
Take a look at these functions, i hope you understand better on update , insert and delete functions..
Code snippets for reading, inserting, updating and deleting a records using asp.net and c# and sql server database
static void Read()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM EmployeeDetails", conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("Id = ", reader["Id"]);
Console.WriteLine("Name = ", reader["Name"]);
Console.WriteLine("Address = ", reader["Address"]);
}
}
reader.Close();
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
"#Id, #Name, #Address)", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Amal Hashim");
cmd.Parameters.AddWithValue("#Address", "Bangalore");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Update()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE EmployeeDetails SET Name=#NewName, Address=#NewAddress WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Munna Hussain");
cmd.Parameters.AddWithValue("#Address", "Kerala");
int rows = cmd.ExecuteNonQuery();
//rows number of record got updated
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Delete()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("DELETE FROM EmployeeDetails " +
"WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
int rows = cmd.ExecuteNonQuery();
//rows number of record got deleted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
Your code should be inserting new records, but I'm not clear on whether it is not doing that, or you mean to update existing records.
Aside from that, understanding that you are new to working with SQL Server, there are a couple of things you should be aware of.
You should use using to automatically dispose resources. This will also close your connection for you so you don't have open connections hanging around.
You should use parameters to protect against sql injection attacks. Another benefit of using parameters in your case is that you don't need to create new commands for every statement.
For example:
using (var connection = new SqlConnection(connectionString)
using (var command = connection.CreateCommand())
{
command.CommandText = "insert into URL_Entries values(#url, #now, #leak)";
command.Parameters.AddWithValue("#now", DateTime.Now);
command.Parameters.AddWithValue("#lead", leak);
// update to correspond to your definition of the table column
var urlParameter = command.Parameters.Add(new SqlParameter("#url", SqlDbType.VarChar, 100));
connection.Open();
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
urlParameter.Value = CleanedURLlist[ok];
command.ExecuteNonQuery();
}
}
Per your comment, if you want to do an update, you'll need to include the parameter(s) that identify the rows to update. If this is a single row, use the primary key value:
command.CommandText = "update URL_Entries set UrlColumn = #url, ModifiedDate = #now where ID = #id";
You're using an INSERT function, that is 'ADD NEW RECORDS'
If you want an update, you'll want an UPDATE function
UPDATE tablename
SET column1 = 'x', column2 = 'y'
WHERE id = z