This question already has answers here:
SqlCommand read one value
(2 answers)
Closed 9 years ago.
I'm fetching date from the database and following is my command for it:
SqlCommand cmd = new SqlCommand("select dob from sample Where cardnum = '" + TextBox1.Text + "'");
How do i save the output of this command into datetime?
At the simplest:
var when = (DateTime)cmd.ExecuteScalar();
However, in the more general case you woulnd need to know about readers and parameters. Or: use a tool like dapper:
var when = conn.Query<DateTime>(
"select dob from sample Where cardnum = #num",
new { num = TextBox1.Text } // parameters, done right
).Single();
But dapper will read entire objects too (mapping properties to columns), not just single values.
Related
This question already has answers here:
How can I add user-supplied input to an SQL statement?
(2 answers)
Closed 4 years ago.
I'm facing a problem with decrementing value with MS Access database.
I get an error
Syntax error in UPDATE Statement
My code:
connection.Open();
command = new OleDbCommand();
command.Connection = connection;
command.CommandText = " update Cards set Count = Count - 1 where Type=" + ct + " ";
command.ExecuteNonQuery();
connection.Close();
Can anyone please help?
You should provide an actual error.
My guess is that count is a keyword and has to be put in square brackets like so [count]
and do use parameters, see Joel's answer
It's not certain, but I strongly suspect it's missing single quotes around ct. Fix it like this:
using (var connection = new OleDbConnection("connection string here"))
using (var command = new OleDbCommand("update Cards set Count = Count - 1 where Type= ?", connection))
{
//have to guess at the OleDbType value. Use the actual column type and length from the database
cmd.Parameters.Add("?", OleDbType.VarWChar, 10).Value = ct;
connection.Open();
command.ExecuteNonQuery();
}
There are several other important fixes in this pattern, too.
This question already has answers here:
OleDbCommand parameters order and priority
(3 answers)
Is order of parameters for database Command object really important?
(3 answers)
OleDbParameters and Parameter Names
(2 answers)
Closed 4 years ago.
I have an access database with my work that I am trying to insert into but I keep getting.
'You cannot add or change a record because a related record is required in table 'Projects'.'
I'm running this query: INSERT INTO Tasks (Assigned,Project,Description) VALUES (#assign,#project,#description)
On this Structure: picture of database structure in access
With this code in C# with an OleDb... commands and connections Which are working fine for other query's:
private void addTaskBTN_Click(object sender, EventArgs e)
{
//the assign id is already known and is of type integer.
string query = "SELECT Project_ID FROM Projects WHERE Project_Name = #project";
OleDbConnection con = new OleDbConnection(con_string);
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#project", projectComboBox.Text);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
project_id = Convert.ToInt16(reader[0]);
Console.WriteLine(project_id);
}
con.Close();
Console.WriteLine("submit: " + project_id + " " + employee_id + " " + descriptionTextBox.Text + " " + monthCalendar1.SelectionStart);
Console.WriteLine(monthCalendar1.SelectionStart);
query = "INSERT INTO Tasks (Assigned,Project,Description) VALUES (#assign,#project,#description)";
con = new OleDbConnection(con_string);
cmd = new OleDbCommand(query, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#project", project_id);
cmd.Parameters.AddWithValue("#assign", employee_id);
cmd.Parameters.AddWithValue("#description", descriptionTextBox.Text.ToString());
//cmd.Parameters.AddWithValue("#deadline", monthCalendar1.SelectionStart);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.Close();
}
I have tried looking at other examples of this problem and I don't understand why I'm getting this error. #project has a valid id number of the primary key for a Project, #assign has a valid employee id as well and #description is string of text. Thanks for any help.
Steve correctly identified the mistake you have to put your parameters in the right order. My fix was to arrange my parameters in order.
This question already has answers here:
Multiple Id's in In clause of SQL Query C# [closed]
(2 answers)
Parameterize an SQL IN clause
(41 answers)
How to add parameter in SELECT query for fieldName IN #fieldName construction [duplicate]
(3 answers)
Closed 4 years ago.
I have a problem with calling by SQL Server database. I have this table
and an object with property Groups, which is something like "all nj sk2".
My query in ssms is
SELECT *
FROM Hours
WHERE class_id = 1
AND groups IN ('all', 'nj', 'sk2')
In C# I'm doing something like this
var query = "SELECT * FROM Hours WHERE class_id = #class_id AND groups LIKE (#groups)";
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#class_id", User.Current.ClassId);
cmd.Parameters.AddWithValue("#groups", User.Current.Groups.Replace(" ", ", "));
}
The only way I made this work was
var groups = "('" + User.Current.Groups.Replace(" ", "', '").Remove(User.Current.Groups.Length - 2);
//above is ('all', 'nj', 'sk2')
var query = "SELECT * FROM Hours WHERE class_id = #class_id AND groups LIKE " + groups;
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#class_id", User.Current.ClassId);
}
But this is not a good solution imo, so if anyone knows what am I doing wrong please help me out. Thanks
This question already has answers here:
ExecuteNonQuery: Connection property has not been initialized.
(7 answers)
Closed 7 years ago.
I keep getting this error saying that "ExecuteScalar has not been initialized" I have new to C# but had a look through google and tutorials and still cant see what the problem is. Its probably a very silly mistake but if anyone could help. Thanks :)
// open connection
myConnection.Open();
// sql command
string Account_Num = txt_acc.Text;
string Pin_num = txt_pin.Text;
SqlCommand check_details = new SqlCommand("select Account_num, Pin_num from Cust_details where Account_num='" + txt_acc.Text + "'and Pin_num ='" + txt_pin.Text + "'");
check_details.Parameters.AddWithValue("#Account_num", txt_acc.Text);
check_details.Parameters.AddWithValue("#Pin_num", txt_pin.Text);
int result = Convert.ToInt32(check_details.ExecuteScalar());
if (result > 0)
{
Console.WriteLine("user exists");
}
else
{
Console.WriteLine("error");
}
}
Looks like you didn't connect your command with connection. Just set it's Connection property to myConnection.
check_details.Connection = myConnection;
or you can set it on your SqlCommand constructor as a second parameter;
SqlCommand check_details = new SqlCommand("yourCommand", myConnection);
or you can use CreateCommand method from your connection;
SqlCommand check_details = myConnection.CreateCommand();
And you are misunderstood the parameterized queries. You still do string concatenation in your sql query but you try to add parameters. That's meaningless.
Use using statement to dispose your connection and command automatically as well.
Also don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.
using(var myConnection = new SqlConnection(conString))
using(var check_details = myConnection.CreateCommand())
{
check_details.CommandText = #"select Account_num, Pin_num from Cust_details
where Account_num = #accnum
and Pin_num = #pinnum";
// I assume your column types as Int
check_details.Parameters.Add("#accnum", SqlDbType.Int).Value = int.Parse(txt_acc.Tex);
check_details.Parameters.Add("#pinnum", SqlDbType.Int).Value = int.Parse(txt_pin.Text);
myConnection.Open();
int result = (int)check_details.ExecuteScalar();
...
}
By the way, there is no point to select Pin_num column in your command since ExecuteScalar ignores it.
This question already has answers here:
How to add line break in C# behind page
(11 answers)
Closed 8 years ago.
I have this line :
cmd.CommandText = "SELECT registeruser_id,registeruser_username, registeruser_email,registeruser_password FROM TestDB_RegisterUser where registeruser_email='" + email + "' and registeruser_password='" + pwd + "' and registeruser_rowstate<3 ";
And when I try to hit Enter on part of the string , I get a big bunch of red lines that indicates that what I did is considered as error .
How do I break it then ? thanks
Yes, because a regular string literal can't include a line break in the source code. You can include one in a verbatim string literal however:
string sql = #"SELECT FOO
FROM BAR
WHERE X=Y";
Or break it with string concatenation:
string sql = "SELECT FOO " +
"FROM BAR " +
"WHERE X=Y";
More importantly, however, you're currently building your SQL in a horribly insecure way. Never include values directly in the SQL like this. Instead, use parameterized SQL and then specify values for the parameters:
string sql = "SELECT FOO FROM BAR WHERE X=#X";
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#X", SqlDbType.NVarChar).Value = "...";
using (var reader = command.ExecuteReader())
{
...
}
}