Hello I'm trying to SELECT multiple rows from table and INSERT them into another I thought that it can be done as following:
This part should select multiple rows:
string sqcom = "SELECT text,castka,rocnik FROM zajsluz WHERE akce='"+tentoradek+"' and rocnik='"+klientClass.Rocnik()+"'";
SqlCommand sc = new SqlCommand(sqcom,spojeni);
spojeni.Open();
sc.ExecuteNonQuery();
spojeni.Close();
This is how I try to INSERT selected rows from SqlCommand sc:
string sqlcom2 = "INSERT INTO zajsluz(akce,text,castka,rocnik) values (#akce,#text,#castka,#rocnik)";
SqlCommand sc2 = new SqlCommand(sqlcom2, spojeni);
sc2.Parameters.AddWithValue("#akce", klientClass.Rocnik());
sc2.Parameters.AddWithValue("#text", ); // I dont know how to define this parameter according to what was selected in SqlCommand sc
spojeni.Open();
sc2.ExecuteNonQuery();
spojeni.Close();
Now I'm wondering hwo can I insert into "#text" (sc2) parameter values from SqlCommand "sc" would you please help me solve this out?
Thanks in advance
Edit: ¨
this is what I tried:
DataSet dt2 = new DataSet();
SqlDataAdapter SDA2 = new SqlDataAdapter("SELECT text,castka FROM zajsluz WHERE akce='" + tentoradek + "' and rocnik='" + klientClass.Rocnik() + "'", spojeni);
SDA2.Fill(dt2);
spojeni.Close();
string sqlcom2 = "INSERT INTO zajsluz(akce,text,castka,rocnik) values (#akce,#text,#castka,#rocnik)";
SqlCommand sc2 = new SqlCommand(sqlcom2, spojeni);
sc2.Parameters.AddWithValue("#akce", zakce.Text);
sc2.Parameters.AddWithValue("#rocnik", klientClass.Rocnik());
sc2.Parameters.AddWithValue("#text", dt2.Tables[0].Columns["text"]);
sc2.Parameters.AddWithValue("#castka", dt2.Tables[0].Columns["castka"]);
spojeni.Open();
sc2.ExecuteNonQuery();
spojeni.Close();
You can directly use insert into & select combination
string sqcom = "INSERT INTO zajsluz(akce,text,castka,rocnik) SELECT rocnik,text,castka,rocnik FROM zajsluz WHERE akce='"+tentoradek+"' and rocnik='" + klientClass.Rocnik() + "'"
SqlCommand sc = new SqlCommand(sqcom,spojeni);
spojeni.Open();
sc.ExecuteNonQuery();
spojeni.Close();
I would try to do this in a single statement if that is possible, i.e. you aren't doing anything to the data in between the two statements.
string sqlcom = "INSERT INTO zajsluz(akce,text,castka,rocnik) SELECT akce,text,castka,rocnik FROM zajsluz WHERE akce='"+tentoradek+"' and rocnik='"+klientClass.Rocnik()+"'";
SqlCommand sc = new SqlCommand(sqcom,spojeni);
spojeni.Open();
sc.ExecuteNonQuery();
spojeni.Close();
Another option would be to use a SQL DataSet/DataTable, which allows you to query and return from SQL an entire table, or a set of rows, that you can then update, delete or insert into. It's described in the following MS article: http://support.microsoft.com/kb/326009/en
This summary answer for your question:
StringBuilder query = new Stringbuilder();
query.AppendLine("INSERT INTO zajsluz(akce,text,castka,rocnik) ");
query.AppendLine("(SELECT #akce, text, castka, #rocnik");
query.AppendLine("FROM zajsluz WHERE akce=#Tentoradek");
query.AppendLine("AND rocnik=#rocnik)");
SqlCommand sc2 = new SqlCommand(sqlcom2, spojeni);
sc2.Parameters.AddWithValue("#Tentoradek", tentoradek);
sc2.Parameters.AddWithValue("#akce", zakce.Text);
sc2.Parameters.AddWithValue("#rocnik", klientClass.Rocnik());
spojeni.Open();
sc2.ExecuteNonQuery();
spojeni.Close();
Related
I used following code for deleting record from my SQL server database but this query deleted all my records. I want to delete just the selected row, not all of them.
SqlCommand cmd = new SqlCommand("DELETE FROM tablename WHERE id=id ", con);
cmd.ExecuteNonQuery();
You should transfer param id, my friend. Refer the code below:
var Id = ""; //set the value that you want to delete
SqlCommand cmd = new SqlCommand("DELETE FROM tablename WHERE id=#Id ", con);
command.Parameters.AddWithValue("#Id", Id);
cmd.ExecuteNonQuery();
I am trying to get a string from a MS Access database and insert into a SQL Server database by using a dataset. But the utf8 string in my SQL statement inserted like ????????? - what can I about this?
This is my code:
OleDbCommand cmd2 = new OleDbCommand("select * from t_about_us", con_access);
OleDbDataAdapter da2 = new OleDbDataAdapter(cmd2);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "t_about_us");
con.Open();
string command2 = "insert into t_about_us(matn,see,metatag_description,metatag_keywords,metatag_author) values('" +
Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(ds2.Tables[0].Rows[0]["matn"].ToString())) + "','" +
Convert.ToInt32(ds2.Tables[0].Rows[0]["see"].ToString()) + "','" +
ds2.Tables[0].Rows[0]["metatag_description"].ToString() + "','" +
ds2.Tables[0].Rows[0]["metatag_keywords"].ToString() + "','" +
ds2.Tables[0].Rows[0]["metatag_author"].ToString() + "')";
SqlCommand cmdd2 = new SqlCommand(command2, con);
cmdd2.ExecuteNonQuery();
con.Close();
By using dynamic SQL to construct an SQL statement with sting literals like 'this' you are implicitly converting the string from Unicode into the single-byte character set used by the SQL Server, and any Unicode characters that do not map to that target character set will be replaced by question marks.
So, for example, with my SQL Server ...
cmd.CommandText = "INSERT INTO myTable (textCol) VALUES ('γιορτή')";
cmd.ExecuteNonQuery();
... will be inserted as ...
????t?
... even though [textCol] is defined as an NVARCHAR column.
The correct approach is to use a parameterized query, like so
cmd.CommandText = "INSERT INTO myTable (textCol) VALUES (#word)";
cmd.Parameters.Add("#word", System.Data.SqlDbType.NVarChar).Value = "γιορτή";
cmd.ExecuteNonQuery();
thank you my friends Finally my code work, this is answer:
OleDbCommand cmd2 = new OleDbCommand("select * from t_about_us", con_access);
OleDbDataAdapter da2 = new OleDbDataAdapter(cmd2);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "t_about_us");
con.Open();
SqlCommand cmd1 = new SqlCommand("INSERT INTO t_about_us(matn,see,metatag_description,metatag_keywords,metatag_author) VALUES (#matn,#see,#metatag_description,#metatag_keywords,#metatag_author)",con);
cmd1.Parameters.Add("#see", System.Data.SqlDbType.BigInt).Value = Convert.ToInt32(ds2.Tables[0].Rows[0]["see"].ToString());
cmd1.Parameters.Add("#matn", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["matn"].ToString();
cmd1.Parameters.Add("#metatag_description", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_description"].ToString();
cmd1.Parameters.Add("#metatag_keywords", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_keywords"].ToString();
cmd1.Parameters.Add("#metatag_author", System.Data.SqlDbType.NVarChar).Value = ds2.Tables[0].Rows[0]["metatag_author"].ToString();
cmd1.ExecuteNonQuery();
con.Close();
I am trying to add a where clause to the following line of code.
the reason for this is because i get the datatable from a dropdown combobox. now i want to filter that table on user name, so that only the user can see their records.
i need help on how to write the where clause into this code.
if you need any more information i will gladding add it.
thank you for any help.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ", comboBox1.Text), con);
After Comments
i added the sql injection protection.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From
#Companydetails where Research_ID = #Researcher_ID"), con);
cmd.Parameters.AddWithValue("#Companydetails", comboBox1.Text);
cmd.Parameters.AddWithValue("#Researcher_ID", usernumber_lab.Text);
but now it is giving me a error saying:
Additional information: Syntax error in query. Incomplete query clause.
is there something else i need to add to finnish this query off?
I would do it as follows;
string query = "Select * from MyTable Where username = #username";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = comboBox1.Text;
}
This way the object will dispose automatically and also you'll be safe from Sql Injection
Please try this
string sql = String.format("Select * From {0} where id = {1}", comboBox1.Text, id);
OleDbCommand cmd = new OleDbCommand(sql,con);
You can just make your sql statement longer:
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From table Where something = something", comboBox1.Text), con);
You don't have to work with multiline or anything. This is only needed in some database managers, but not in a c# sql statement.
If you would like
OleDbCommand cmd = new OleDbCommand(String.Format("Select * From {0} WHERE username='{1}'", comboBox1.Text,username.Text), con);
You can try the below code
OleDbCommand cmd = new OleDbCommand(string.Format(
"SELECT * FROM {0} WHERE Username = '{1}'",
comboBox1.Text, userName), con);
Here is my Query:
string Select = "Update DC set Password = '" + txtPass.Text + "' WHERE ID ="+Convert.ToInt32(cbxDocs.SelectedIndex + 1);
con = new OleDbConnection();
this.readconfile = new ReadConfigFile();
con.ConnectionString = this.readconfile.ConfigString(ConfigFiles.ProjectConfigFile);
con.Open();
cmd = new OleDbCommand(Select, con);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
I don't know what is wrong but it gives me an error message that "Syntax error in UPDATE STATEMENT".
I have two fields in my table 'DC' ID and Password, nothing else.
PASSWORD is reserve word enclose it in square brackets like [Password], so your query should start like:
"Update DC set [Password]....
Consider using parameterized query, this will save you from Sql Injection
I think u don't need the ' on ur query and Password is reserved in almost every ddb.
And you could use parameters to avoid the concat with the +
Ex.
string pass = TxtPass.Text;
int s = cbxDocs.SelectedIndex+1;
string Select = "Update DC set Password = #a WHERE ID = #o";
OleDbCommand cmd = new OleDbCommand(Select, conn);
cmd.Paramaters.AddWithValue("#a", pass);
cmd.Parameters.AddWithValue("#o", s);
//everything else....
Here is what I am trying to achieve. I want to get two values from the same row in the same table and store them into two variables. I am doing this in MVC.
Here is what I am doing :
SqlCommand amd = new SqlCommand("SELECT [Value1] FROM [ExampleTable] where Ad_name=#adname", con);
SqlCommand bmd = new SqlCommand("SELECT [Value2] FROM [ExampleTable] where Ad_name=#adname", con);
amd.Parameters.AddWithValue("#adname", aname);
bmd.Parameters.AddWithValue("#adname", aname);
imgpath1 = amd.ExecuteScalar().ToString();
imgpath2 = bmd.ExecuteScalar().ToString();
But here is what I want:
SqlCommand amd = new SqlCommand("SELECT [Value1] AND [Value2] FROM [ExampleTable] where Ad_name=#adname", con);
amd.Parameters.AddWithValue("#adname", aname);
imgpath1 = Value1;
imgpath2 = Value2;
How can I achieve that without writing multiple queries? Thanks
See the method of SqlCommand ExecuteReader that return a SqlDataReader:
using(var command = new SqlCommand("SELECT [Value1], [Value2] FROM [ExampleTable] where Ad_name=#adname", con))
{
command.Parameters.AddWithValue("#adname", aname);
using(var reader = command.ExecuteReader())
{
while (reader.Read())
{
imgpath1 = reader[0];
imgpath2 = reader[1];
}
}
}
Your second SQL command isn't going to work, and if you want to values you wont be able to do a scalar query...
Try:
SqlCommand command = new SqlCommand("SELECT [Value1], [Value2] FROM [ExampleTable] where Ad_name=#adname", con);
And add the parameter.
Then you can
var reader = command.ExecuteReader();
and get the values by
reader["[Value1]"];
reader["[Value2]"];
Essentially, doing a scalar query is meant for queries which only return a single value.
Use comma as separator between retrieved columns, use GetOrdinal to avoid constant numbers like [1] and [2].
const string ColumnOne = "ColumnOne";
const string ColumnTwo = "ColumnTwo";
var sqlCmd = new SqlCommand("select [VALUE1] as " + ColumnOne + ", [VALUE2] as " + ColumnTwo + " from table", sqlConn);
var sqlCmdReader = sqlCmd.ExecuteReader();
if (sqlCmdReader.Read())
{
var resultOne= sqlCmdReader.GetString(sqlCmdReader.GetOrdinal(ColumnOne));
var resultTwo= sqlCmdReader.GetString(sqlCmdReader.GetOrdinal(ColumnTwo ));
}
You call the database just one time with the method ExecuteReader.
Notice how the single columns required are listed after the SELECT separated by a comma.
This is the common basic syntax required for a SELECT statement
This method returns a DataReader that you can use to get single values of a row.
I suppose that your query returns just one record, so, the loop is not strictly necessary.
SqlCommand amd = new SqlCommand("SELECT [Value1], [Value2] FROM [ExampleTable] where Ad_name=#adname", con);
amd.Parameters.AddWithValue("#adname", aname);
SqlDataReader reader = amd.ExecuteReader();
while(reader.Read())
{
imgPath1 = reader[0].ToString();
imgPath2 = reader[1].ToString();
}