I want to sum all values of a column (ttl), and store result in a variable (sum), I tried some code snippets, but I didn't get any success.
SqlCommand cmd1 = new SqlCommand("Select sum(ttl) from feereceipt where std_id = '"+ textBox1.Text +"'",con);
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
sum = Convert.ToInt32(dr[0]);
MessageBox.Show(sum.ToString());
con.Close();
}
In your code, you should close the connection after the loop, closing the connection inside the loop will cause an error:
while (dr.Read())
{
sum = Convert.ToInt32(dr[0]);
MessageBox.Show(sum.ToString());
}
con.Close();
Sum should return a single value, so you can simply get the value like this:
int sum = Convert.ToInt32(cmd1.ExecuteScalar());
Adding a variable directly to query makes it vulnerable for injections. Use parameters instead:
SqlCommand cmd1 = new SqlCommand("Select sum(ttl) from feereceipt where std_id = #id",con);
cmd1.Parameters.Add("#id", SqlDbType.VarChar).Value = textBox1.Text;
Related
I am using this code to save hours but with the use ShowFooter property, can I enter the spaces under the columns in total how to have a use code and summaryitem format what should it be?
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO LogBook (Se,Me)VALUES(,#Se,#Me)", connection);
cmd.Parameters.AddWithValue("#Se", Convert.ToDateTime(textEdit7.Text).ToString("HH:mm"));
cmd.Parameters.AddWithValue("#Me", Convert.ToDateTime(textEdit8.Text).ToString("HH:mm"));
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
After you are done inserting the data in the database , you can simply use a datareader and achieve your goal :
int totalhours;
SqlCommand cmd = new SqlCommand("Select Se,Me from LogBook",con)
SqlDataReader dr = cmd.ExecuteREader();
While (dr.Read)
{
totalhours = totalhours + Convert.ToInt32(dr[0].ToString().Split(':')(0)) + Convert.ToInt32(dr[1].ToString().Split(':')(0));
}
MessageBox.Show(totalhours);
Conversion failed when converting the nvarchar value 'A' to data type int.
private void linksdetail(string id)
{
SqlConnection con = new SqlConnection(con_string);
con.Open();
SqlCommand cmd = new SqlCommand(" select a.solution_title,b.solution_sub_id,b.solutions_id,a.url from cms_solution_viewnew a, cms_solution_viewnew b where a.row_id = b.solution_sub_id and b.solutions_id='" + id + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
HyperLink1.Text = dr["solution_title"].ToString();
HyperLink1.NavigateUrl = dr["url"].ToString();
}
dr.Close();
con.Close();
}
How to solve it please help me.
solutions_id column data type is integer type and value of id is 9
Error message is pretty self explanatory. You try to assign sequence of characters to int typed column. Based on your example values, you don't need to use single quotes with your numeric columns. You can change your
b.solutions_id = '" + id + "'"
to
b.solutions_id = " + id
but as a better way, use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataReader automatically instead of calling Close methods manually.
using(var con = new SqlConnection(con_string))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "select a.solution_title,b.solution_sub_id,b.solutions_id,a.url from cms_solution_viewnew a, cms_solution_viewnew b where a.row_id = b.solution_sub_id and b.solutions_id = #id";
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id;
con.Open();
using(var dr = cmd.ExecuteReader())
{
// Do your stuff
}
}
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);
I want to retrieve the resulting value of a select statement into a string variable. Like this:
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
cmd1.ExecuteNonQuery();
I want to place the selected treatment value into a string variable. How can I do this?
Use ExecuteReader() and not ExecuteNonQuery(). ExecuteNonQuery() returns only the number of rows affected.
try
{
SqlDataReader dr = cmd1.ExecuteReader();
}
catch (SqlException oError)
{
}
while(dr.Read())
{
string treatment = dr[0].ToString();
}
Or better, use a using statement for it.
using(SqlDataReader dr = cmd1.ExecuteReader())
{
while(dr.Read())
{
string treatment = dr[0].ToString();
}
}
But if your SqlCommand returns only 1 column, you can use the ExecuteScalar() method. It returns first column of the first row as follows:-
cmd.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
string str = Convert.ToString(cmd.ExecuteScalar());
Also you can open your code to SQL Injection. Always use parameterized queries. Jeff has a cool blog article called Give me parameterized SQL, or give me death. Please read it carefully. Also read DotNetPerl SqlParameter article. SQL Injection very important when you are working queries.
Execute Scalar: Getting Single Value from the Database method to retrieve a single value (for example, an aggregate value) from a database.
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
if(cmd.ExecuteScalar()==null)
{
var treatment = cmd.ExecuteScalar();
}
Other Way: ExecuteReader()
try
{
cmd1.CommandText ="SELECT treatment FROM appointment WHERE patientid=#patientID";
cmd1.Parameters.AddWithValue("#patientID", this.DropDownList1.SelectedValue);
conn.Open();
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
int PatientID = int.Parse(dr["treatment"]);
}
reader.Close();
((IDisposable)reader).Dispose();//always good idea to do proper cleanup
}
catch (Exception exc)
{
Response.Write(exc.ToString());
}
the answer:
String res = cmd1.ExecuteScalar();
the remark: use parametrized query to prevent sql injection
There is a lot wrong with your example code.
You have inline sql, which opens you up to sql injection in a major way.
You are using ExecuteNonQuery() which means you get no data back.
string sSQL = "SELECT treatment FROM appointment WHERE patientid = #patientId";
OleDbCommand cmd1 = new OleDbCommand(sSQL, GetConnection()); // This may be slight different based on what `GetConnectionReturns`, just put the connection string in the second parameter.
cmd1.Parameters.AddWithValue("#patientId", text);
SqlDataReader reader = cmd1.ExecuteReader();
string returnValue;
while(reader.Read())
{
returnValue = reader[0].ToString();
}
You just need to use the ExecuteScalar method of the command - this will give you the value at the first row and column of the result set.
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
var result = cmd1.ExecuteScalar();
If your SQL statement returns more than one row/column then you can use ExecuteReader().
You need to use OleDbAdapter.
string connection = "your connection";
string query = "SELECT treatment FROM appointment WHERE patientid = " + text;
OleDbConnection conn = new OleDbConnection(connection);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.Fill(dataset);
SqlConnection dbConnect = new SqlConnection("your SQL connection string");
string name = " 'ProjectName' ";
string strPrj = "Select e.type, (e.surname +' '+ e.name) as fulln from dbo.tblEmployees e where id_prj = " + name;
SqlCommand sqlcmd = new SqlCommand(strPrj, dbConnect);
SqlDataAdapter sda = new SqlDataAdapter(strPrj, dbConnect);
ds = new DataSet();
sda.Fill(ds);
dbConnect.Open();
sqlcmd.ExecuteNonQuery();
dbConnect.Close();
I've been writing a lot of web services with SQL inserts based on a stored procedure, and I haven't really worked with any SELECTS.
The one SELECT I have in mind is very simple.
SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization
WHERE AD_SID = #userSID
However, I can't figure out based on my current INSERT code how to make that into a SELECT and return the value of ReturnCount... Can you help? Here is my INSERT code:
string ConnString = "Data Source=Removed";
string SqlString = "spInsertProgress";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("attachment_guid", smGuid.ToString());
cmd.Parameters.AddWithValue("attachment_percentcomplete", fileProgress);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
Here is where you are going wrong:
cmd.ExecuteNonQuery();
You are executing a query.
You need to ExecuteReader or ExecuteScalar instead. ExecuteReader is used for a result set (several rows/columns), ExecuteScalar when the query returns a single result (it returns object, so the result needs to be cast to the correct type).
var result = (int)cmd.ExecuteScalar();
The results variable will now hold a OledbDataReader or a value with the results of the SELECT. You can iterate over the results (for a reader), or the scalar value (for a scalar).
Since you are only after a single value, you can use cmd.ExecuteScalar();
A complete example is as follows:
string ConnString = "Data Source=Removed";
string userSid = "SomeSid";
string SqlString = "SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization WHERE AD_SID = #userSID;";
int returnCount = 0;
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#userSID", userSid);
conn.Open();
returnCount = Convert.ToInt32(cmd.ExecuteScalar());
}
}
If you wanted to return MULTIPLE rows, you can use the ExecuteReader() method. This returns an IDataReader via which you can enumerate the result set row by row.
You need to use ExecuteScalar instead of ExecuteNonQuery:
String query = "SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization WHERE AD_SID = #userSID ";
using (OleDbConnection conn = new OleDbConnection(ConnString)) {
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("userSID", userSID.ToString());
conn.Open();
int returnCount = (Int32) cmd.ExecuteScalar();
conn.Close();
}
}
cmd.executescalar will return a single value, such as your count.
You would use cmd.executereader when you are returning a list of records