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();
}
Related
string s = "select idviagem from tbviagem where dia like '" + idatxt.Text + "'";
cmd = new SqlCommand(s, con);
I need the idviagem from the table tbviagem to put in idviagem from tbpassageiro (it's FK on tbpassageiro) , but i need the get idviagem from idatxt.Text it's a DateTime format, but doing the insert (look down) gives me the error:
Conversion failed when converting the nvarchar value 'select idviagem from tbviagem where dia like '06/12/2018 00:00:00'' to data type int.'
but idviagem is a int, of course .
string q = "insert into tbpassageiro (nome,cc,fotocc,idviagem) values(#n,#cc,#p,#iv)";
cmd = new SqlCommand(q, con);
con.Open();
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.AddWithValue("#iv", s);
cmd.ExecuteNonQuery();
You should never execute SQL statements like that but use parameters. You are using parameters for your second statement but not doing it for the first one.
Having said that, you are trying to use the query string s as the parameter value for #iv. Instead you should ExecuteScalar in first and use the result of it in second.
However, you can both get the idviagem value and do the insert in one single statement like this:
string q = #"insert into tbpassageiro
(nome,cc,fotocc,idviagem)
select #n,#cc,#p,idViagem from tbviagem where dia like #dia";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.Add("#dia", SqlDbType.VarChar).Value = idatxt.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Note: I don't suggest using AddWithValue, prefer Add instead.
EDIT: For sampling with a Datetime dia field:
DateTime dt;
cmd.Parameters.Add("#dia", SqlDbType.DateTime);
if (DateTime.TryParse(idatxt.Text, out dt))
{
cmd.Parameters["#dia"].Value = dt;
}
else
{
cmd.Parameters["#dia"].Value = DBNull.Value;
}
If idatxt is for getting a date\datetime value it would be much easier to use DateTimePicker to get a valid DateTime value.
It looks like you are passing the query string s as the parameter value for #iv instead of the result of that query.
I suggest executing your command cmd and passing the result value to #iv:
string s = "select idviagem from tbviagem where dia like '" + idatxt.Text + "'";
cmd = new SqlCommand(s, con);
con.Open();
Int32 resultValue = (Int32) cmd.ExecuteScalar();
string q = "insert into tbpassageiro (nome,cc,fotocc,idviagem) values(#n,#cc,#p,#iv)";
cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.AddWithValue("#iv", resultValue);
cmd.ExecuteNonQuery();
I want to return the total of the values in record "hours" on the table "Courses" from my sql database I tried this code but it doesn't work:
SqlCommand cmd = new SqlCommand("Select Courses.hours from Courses inner join Sched on Courses.Id = Sched.SCourses ", con2);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
SqlCommand cmd2 = new SqlCommand("Select sum(hours) as totalHours from Courses");
Label3.Text = cmd2.ToString();
}
You are not specified the connection for your sql command cmd2 .
Try this .
SqlCommand cmd2 = new SqlCommand("Select sum(hours) as totalHours from Courses",con2);
Label3.Text = cmd2.ExexcuteScalar().ToString();
There are two problems in the code: doing while (rdr.Read()) you loop through all rows of result set and execute Select sum(hours)... as many times as many rows you get in the first query.
Depends on requirements, you might want to do if instead of while
if (rdr.Read())
Next, cmd2.ToString(); will not output the result of the query. You should either use ExecuteReader as in the first case, or use ExecuteScalar
if (rdr.Read())
{
SqlCommand cmd2 = new SqlCommand("Select sum(hours) as totalHours from Courses", con2);
Label3.Text = cmd2.ExecuteScalar().ToString();
}
Why are you totaling your hours using separate queries. Use group by clause and run only once.
SqlCommand cmd = new SqlCommand("Select Courses.id, Sum(Courses.hours) from Courses inner join Sched on Courses.Id = Sched.SCourses group by Course.id")
SqlDataReader rdr = cmd.ExecuteReader();
Label3.Text = cmd.ExecuteScalar().ToString();
Hope it will help.
I have a datagridview. In this DGV first colum is a combobox column. I want to make, when this combobox value is selected next fild will be filled automatically from database. But there shows a error.
No value given for one or more required parameters on
OleDbDataReader dr1 = cmd1.ExecuteReader();
I post the code. Please help me.
OleDbConnection con = new OleDbConnection(conn);
con.Open();
for (int i = 0; i < dgv.Rows.Count; i++)
{
string query = "select Description from General where AccCode='" +
dgv.Rows[i].Cells[0].Value +
"' and conpanyID='" +
label1.Text + "'";
OleDbCommand cmd1 = new OleDbCommand(query, con);
//OleDbDataAdapter daBranchName = new OleDbDataAdapter(cmd);
OleDbDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
dgv.Rows[i].Cells[1].Value = dr1["Description"].ToString();
}
}
con.Close();
This kind of string concatenations are open for SQL Injection attacks.
Use parameterized queries instead.
string query = "select [Description] from [General] where AccCode= ? and conpanyID= ?";
OleDbCommand cmd1 = new OleDbCommand(query, con);
cmd1.Parameters.AddWithValue("#acc", dgv.Rows[i].Cells[0].Value);
cmd1.Parameters.AddWithValue("#ID", label1.Text);
As HansUp pointed, Description and General are reserved keywords. Use them with square brackets like [Description] and [General]
As suggested, use parameterized queries.
As far as the error is concerned, I'm guessing this field name is wrong:
conpanyID=
should be:
companyID=
Use Parameters, otherwise it will open for sql injection attacks.
string query = "select [Description] from General where AccCode=? and conpanyID=?";
now you can set parameters
cmd.Parameters.AddWithValue("#p1", val1);
cmd.Parameters.AddWithValue("#p2", val2);
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();
I have two columns syntax and query in my table Table1. Syntax contains data called po and a query called select * from po_pomas_pur_order_hdr where pomas_pono =. I got this query value by using
SqlDataAdapter da = new SqlDataAdapter("select query from Table1 where syntax = '" + textBox1.Text + "'", conn);
And my problem is that I need to dynamically pass another value inside the query which I retrived using dataadapter like this:
SqlDataAdapter da1 = new SqlDataAdapter(da.tostring() +"'"+ textBox1.Text +"'", conn)
The resulting query should be like this:
select * from po_pomas_pur_order_hdr where pomas_pono = '2PO/000002/09-10'
But it is not possible. How to get a query like this? Any suggestion?
SqlDataAdapter is used to fill datasets and datatables. You cannot obtain the result of a query with ToString(). I think you want to use SqlCommand to execute your first query to retrieve the actual query to run from the database like this:
string query = null;
using (var command = new SqlCommand("select query from Table1 where syntax = #Syntax", conn))
{
command.Parameters.AddWithValue("#Syntax", textBox1.Text);
query = command.ExecuteScalar(); // this assumes only one query result is returned
}
Then you can use the data adapter to fill it:
SqlDataAdapter da1 = new SqlDataAdapter(query +"'"+ textBox1.Text +"'", conn);
Although I would suggest to use parameters for that as well.
in this way is more safe: dotnetperls
He check the "'" and the "\", check the type of the fields etc...
Code from the example above (is the same for insert delete and update):
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Name", dogName));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}", weight, name, breed);
}
}
I suggest you to use SqlParameters. Here is example how to use DataAdapter and parameters.
Provided that you have a DataSet you intend to fill using the adapter and that you adjust the queries to use parameters in order to avoid sql injection you should be able to use something like this:
string query;
using(var sqlCommand = new SqlCommand(
"select query from Table1 where syntax=#syntax", conn))
{
sqlCommand.Parameters.AddWithValue("syntax", textBox1.Text);
query = (string)sqlCommand.ExecuteScalar();
}
using(var dataAdapter = new SqlDataAdapter())
using(var dataCommand = new SqlCommand(query, conn))
{
dataCommand.Parameters.AddWithValue("parameter", poNumber);
dataAdapter.SelectCommand = dataCommand;
dataAdapter.Fill(myDataSet);
}