I'm getting an error while trying to insert a date into database, here is the insert command:
cmd.CommandText = "INSERT INTO Customer([date1])VALUES(Convert.ToDateTime(date1.Text))
the error is :
String was not recognized as a valid datetime.
What you have here is a string.
Convert.ToDateTime(date1.Text)
will never compile to what you need. It will be send as such in the DB. Use a parameterized command and pass the result of this in a parameter.
For instance:
string sqlstring = "INSERT INTO Customer([date1])VALUES(#Date)";
SqlCommand cmd = new SqlCommand(sqlstring, conn);
SqlParameter par = new SqlParameter("#Date", Convert.ToDateTime(date1.Text));
cmd.Parameters.Add(par);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Related
I have a program that is to take a couple inputs and do stuff to them then store them in a local database (using SQL Server).
I have the following code for the connection:
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
String st = "INSERT INTO data(Username,Password, Hash, EncryptedPassword)";
SqlCommand cmd = new SqlCommand(st, con);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Hash", savedPasswordHash);
cmd.Parameters.AddWithValue("#EncryptedPassword", FinalEncryptedPass);
cmd.ExecuteNonQuery();
con.Close();
It fails at the cmd.ExecuteNonQuery(); line, and throws this exception :
Incorrect syntax near ')'
I'm not even really sure where to start, as I haven't done any of this since college (107 years ago). Can anybody help me get started? I've been scouring but nothing seems to be working.
Maybe your insert should look like this:
INSERT INTO data (Username, Password, Hash, EncryptedPassword)
VALUES (#Username, #Password, #Hash, #EncryptedPassword)
The VALUES clause will need to be within the insert statement string. I would also recommend a using block instead of directly opening the SqlConnection, as will automatically close the connection upon exit whether by completion or error. While technically there isn't a difference between using String and string as in your command text, String would most often be used to reference a class while string is typically used in object references such as the case here.
string connectionString = #"YourConnectionString";
string st = "INSERT INTO data(Username,Password, Hash, EncryptedPassword) VALUES (#Username, #Password, #Hash, #EncryptedPassword)";
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(st1, con);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Hash", savedPasswordHash);
cmd.Parameters.AddWithValue("#EncryptedPassword", FinalEncryptedPass);
con.Open();
cmd.ExecuteNonQuery();
}
I am facing this error while i was trying to convert the session object type to int, I need to use that value in another query which is of datatype int.
SqlConnection sqlConnection1 = new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=Remember;server=DESKTOP-59SGH72\\SQLEXPRESS;Trusted_Connection=True;Database=sport");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "select user_id from users where user_name='" + Session["usern"] + "'";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
Session["userid"] = reader;
var uid = Convert.ToInt16(Session["userid"]);
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
Please help me with this error !!
first of all your code is terrible -- it is totally going to get hacked by an injection attack. You should be using a parameterized query.
as to your question, something like this would work but you really should be doing lots of error checking and sanity checks:
reader = cmd.ExecuteReader();
reader.Read();
Session["userid"] = reader[0];
You probably should have looked at the documentation which has some nice examples
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
I've been stuck on this error for a while, in vb.net trying to connect to SQL and pull data from a table within a day, using parameters to do this, a datetimepicker - the data saved to SQL is in a custom datetime format dd/MM/yyyy HH:mm:ss,
When i execute my code i get
"Must declare the scalar variable "#line"
When i remove the code " WHERE [line] = #line and date >= #startdata AND date < #enddata " it works but shows all the data without the date range as it should.
connect()
DataGridView1.AutoGenerateColumns = True
cmd.Parameters.Clear()
cmd.CommandText = #"SELECT board, defect, date, detail_x, detail_y,
detail_width, detail_height
FROM [sqlccmdefects]
WHERE [line] = #line
and date >= #startdata
AND date < #enddata";
cmd.Parameters.Add("#line", SqlDbType.VarChar, 30).Value = Form1.line.Text
cmd.Parameters.Add("#startdata", SqlDbType.DateTime).Value = DateTimePicker1.Value
cmd.Parameters.Add("#enddata", SqlDbType.DateTime).Value = DateTimePicker2.Value
cmd.ExecuteScalar()
Dim dataAdapter1 = New SqlDataAdapter(cmd.CommandText, con.ConnectionString)
Dim table1 As New DataTable()
table1.Locale = System.Globalization.CultureInfo.InvariantCulture
dataAdapter1.Fill(table1)
Me.BindingSource1.DataSource = table1
DataGridView1.DataSource = BindingSource1
disconnect()
All i get is a blank Datagridview with the scalar error.
There looks to be a couple of issues in the code you posted,
Try this:
'SQL Connection
Dim sqlCon As New SqlConnection("Server=.;Database=dummy;Trusted_Connection=True;")
'SQL Command
Dim sqlCmd As New SqlCommand("", sqlCon)
sqlCmd.CommandText = "SELECT board, defect, date, detail_x, detail_y, detail_width, detail_height FROM [sqlccmdefects] WHERE [line] = #line and date >= #startdata AND date < #enddata"
'SQL Command Params
sqlCmd.Parameters.Add("#line", SqlDbType.VarChar, 30).Value = "WHATEVER"
sqlCmd.Parameters.Add("#startdata", SqlDbType.DateTime).Value = "2015-07-21"
sqlCmd.Parameters.Add("#enddata", SqlDbType.DateTime).Value = "2015-07-23"
'Data Adapters
Dim dataAdapter1 = New SqlDataAdapter(sqlCmd)
Dim table1 As New DataTable()
'NOT SURE WHAT THIS DOES?
table1.Locale = System.Globalization.CultureInfo.InvariantCulture
'Attach to the GV
dataAdapter1.Fill(table1)
DataGridView1.AutoGenerateColumns = True
BindingSource1.DataSource = table1
DataGridView1.DataSource = BindingSource1
ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row.
Use cmd.ExecuteReader() or cmd.ExecuteNonQuery() instead of cmd.ExecuteScalar()
cmd.ExecuteScalar()
will execute the command – consuming the parameters – and throwing away any result (use ExecuteNonQuery when there is no result: saves setting up to return values).
When you fill the data adapter the command will be run again. But this time there are no parameters, and SQL fails on the first undefined identifier.
So: don't execute the command, instead pass the (unexecuted) command to the (single argument) data adapter constructor.
im getting this error when i changed my textbox to datetimepicker
here is my code
Dim cmd As SqlCommand = sqlconn.CreateCommand
sqlconn.Open()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "AddOfficeEquipmentProfile"
cmd.Parameters("#OE_PurchaseDate").Value = dtpPurchaseDate.Value
cmd.ExecuteNonQuery()
sqlconn.close
this is my stored procedure as follows
CREATE PROCEDURE AddOfficeEquipmentProfile
(
#OE_PurchaseDate smalldatetime,
)
AS
INSERT INTO tblOfficeEquipmentProfile (OE_PurchaseDate)
VALUES (#OE_PurchaseDate)
GO
I think the error message is quite straightforward. You need to add the parameter before attempting to set its value.
cmd.CommandText = "AddOfficeEquipmentProfile"
cmd.Parameters.Add("#OE_PurchaseDate",SqlDbType.SmallDateTime)
cmd.Parameters("#OE_PurchaseDate").Value = dtpPurchaseDate.Value
I am trying to use the following query
Dim sqlQry As String = "SELECT * FROM tblTest where Name=#NM and Rank=#RN"
Then I fill my dataadapter by
Dim dAdt As New SqlDataAdapter(sqlQry, conStr)
But do not know where to put the parameters that I have set after where clause.
You can use the parameters like this:
Dim adapter As SqlDataAdapter = New SqlDataAdapter()
' Create the SelectCommand.
Dim command As SqlCommand = New SqlCommand("SELECT * FROM tblTest where Name=#NM and Rank=#RN", connection)
' Add the parameters for the SelectCommand.
command.Parameters.Add("#NM", SqlDbType.NVarChar, 15)
command.Parameters.Add("#RN", SqlDbType.NVarChar, 15)
adapter.SelectCommand = command
Check this MSDN Document
Create a parameter
SqlParameter param = new SqlParameter();
param.ParameterName = "#RN";
param.Value = inputCity;
Then add the param to your Sql Command.
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add(param);
If I understand what you're asking, you need to create an instance of an SqlCommand and use your sqlQry with that. Then use SqlCommand.Parameters.Add() or SqlCommand.Parameters.AddWithValue() to add your parameters. Initialize your SqlDataAdapter with the SqlCommand instead of the String you've created.
Using connection As New SqlConnection(conStr)
Dim command As New SqlCommand(sqlQry, connection)
command.Parameters.Add("#NM", SqlDbType.NVarChar, 100).Value="Your Value"
command.Parameters.AddWithValue("#RN", "Your Value")
Dim adapter As New SqlDataAdapter(command)
adapter.Fill(dataSet)
Return dataSet
End Using