Insert DateTime into Database - asp.net

I have a DateTime field in my SQL database which I want to write a time to, but how do I do this?
I'm wanting to do it as a timestamp, so when the user clicks an "add" button it adds the data to the other fields, and a timestamp into the DateTime field, but I keep getting the following error
Conversion failed when converting date and/or time from character string.
This is my current code in the CS file
insertSQL = "INSERT INTO Posts (TopicID, PostBody, PostDate, UserID)"
+ "VALUES ('" + topic + "', '" + newPostText + "', '" + DateTime.Now.ToString() + "', '" + User_ID + "')";
Please note I'm wanting to display as much time info as I can. Eg 23/05/2012 10:58:00 a.m.

Your implementation is prone to SQL Injection. To resolve that, AND your DateTime issue, use parameters - http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Something like this:
string commandText = "INSERT INTO Posts (TopicID, PostBody, PostDate, UserID)"
+ "VALUES (#Topic, #NewPostText, #PostDate, #UserID)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("#Topic", "My Topic");
command.Parameters.AddWithValue("#NewPostText", "Post text goes here");
command.Parameters.AddWithValue("#PostDate", dateObject);
command.Parameters.AddWithValue("#UserID", "UserA");
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
}
catch (Exception)
{
// Handle Errors
}
}

Are you asking for strtotime() ?
<?php
$d = date('y-m-d');
echo date('d M Y',strtotime( $d ));
echo "<br>";
echo date('Y-m-d H:i:s'); ?>
sigh, my fault, it's for Php~

Related

'Parameters supplied for object 'AdminAssistant' which is not a function. If the parameters are intended as a table hint, a WITH keyword is required.'

While inserting values into the database i am getting error which is said in subject dont know what i am missing.
string ImagePath = "";
string str = "insert into AdminAssistant() values('"+TextBox7.Text+ "','" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + DropDownList2.Text + "','" + TextBox4.Text + "','" + DropDownList1.Text+ "','" + TextBox9.Text + "','"+ImagePath+"','"+DateTime.Now+"','Active')";
SqlCommand cmd = new SqlCommand(str,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Admin Created Successfully.....!!!";
Below is the Query
Create Table AdminAssistant
(
A_ID int identity(1,1) not null primary key,
Aname varchar(20),
Aphone varchar(16),
Amail varchar(20),
A_Address varchar(150),
A_City varchar(20),
A_Gender varchar(10)NOT NULL CHECK (A_Gender IN('Male', 'Female')),
A_Password varchar(20),
Aroll varchar(20)NOT NULL CHECK (Aroll IN('SuperAdmin', 'Admin')),
MetaDescription varchar(256),
Media varchar(40),
RegisterDate datetime,
A_Status varchar(20)NOT NULL CHECK (A_Status IN('Active', 'Disable'))
)
I think this values should inserted into database despite that it is giving error.
The error is probably caused by the presence of the parenthesys after the name of the table, but this is a simple fix to do.
Your real problem lies in the string concatenation for your values.
This is a no-no in the sql world because it could be the source of many parsing bugs (for example, the presence of a single quote in the values could break the syntax and DateTime.Now is converted to a string following rules the not always are understood by the sql parser engine).
But most important is the possibility of Sql Injection.
Here some links to start your discovery for this big security risk
How can I explain Sql Injection without technical jargon.
How does the SQL injection from the “Bobby Tables” XKCD comic work?
So the only fix is through a parameterized query.
string str = "insert into AdminAssistant
(Aname,Aphone,Amail,A_Address,A_City,A_Gender,A_Password,
Aroll,MetaDescription,Media,RegisterDate,A_Status)
values(#name,#phone,#mail,#address,#city,#gender,#pass
#roll,#descr,#media,#regdata,'Active')";
using(SqlConnection con = new SqlConnection(......))
using(SqlCommand cmd = new SqlCommand(str, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = TextBox7.Text;
... other varchar parameters
cmd.Parameters.Add("#regdataq", SqlDbType.DateTime).Value = DateTime.Now;
... complete the parameters collection
cmd.ExecuteNonQuery();
}
And, I have forget to talk about storing passwords in clear text into a database. This is another very important consideration for your security. Here another link with useful info
Best way to store password in database

How to RETURN #Identity of instert data in spl in asp.net

I'm inserting data in a table with this code below.
SqlCommand cmd = new SqlCommand("INSERT INTO Users (Username,Password,FirstName,lastName,PhoneNumber,Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)"
+ ("VALUES ('" + TextBox1.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','User','0','" + Date + "')"), con);
cmd.ExecuteNonQuery();
I want to get Id of inserting Value in database which I save new data in table anyone have any idea what can i have to add in a code so i can RETURN #Identity of insert value in table and use that id some other code.
Thank you
First use parametrized queries (to avoid SQL Injection attack)
var sql = "INSERT INTO Users (Username,Password,FirstName,lastName,PhoneNumber,Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)" +
"values (#username, #password, #firstname, #lastname, #phone, #address, #city, #state, #country, #zipcode, #usertype, #payout, #timedate);" +
"select SCOPE_IDENTITY()";
var cmd = new SqlCommand(sql);
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox3.Text);
cmd.Parameters.AddWithValue("#firstname", TextBox4.Text);
cmd.Parameters.AddWithValue("#lastname", TextBox5.Text);
cmd.Parameters.AddWithValue("#phone" TextBox6.Text);
//and so on
var id = Convert.ToInt32(cmd.ExecuteScalar());
SCOPE_IDENTITY returns last id created for inserted row in given scope. This way you get back id. Use ExecuteScalar() method that returns one value from first row, first column.
Also do not store clear text as password, use some hashing method.
change your sql and code like as below
for sql 2005+
INSERT INTO Users (UserId,otherdata...)
OUTPUT INSERTED.ID
VALUES(#UserId, #othervalues...)
for sql 2000
INSERT INTO aspnet_GameProfiles(UserId,otherdata...)
VALUES(#UserId, #othervalues...);
SELECT SCOPE_IDENTITY()
And then
Int32 newId = (Int32) myCommand.ExecuteScalar();
Suggestion:
Make use of parameterize query to avoid sql injection attack....
The simplest way would be to append "SELECT SCOPE_IDENTITY()" to your SQL statement. You should parametrize your query to avoid SQL Injection, and it would look something like:
string sql = #"
INSERT INTO Users
(Username,Password,FirstName,lastName,PhoneNumber,
Address,City,State,Country,ZipCode,UserType,PayOut,TimeDate)
VALUES(#Username, #Password, ...)
SELECT SCOPE_IDENTITY()
";
SqlCommand cmd = new SqlCommand(sql, ...);
... append parameters ...
var identity = (decimal) cmd.ExecuteScalar();
If your identity column is an integer, you can either cast from decimal to integer, or do the cast in SQL Server, e.g.
string sql = #"
INSERT INTO Users
...
SELECT CAST(SCOPE_IDENTITY() AS INT)
";
SqlCommand cmd = new SqlCommand(sql, ...);
... append parameters ...
var identity = (int) cmd.ExecuteScalar();
Note that SCOPE_IDENTITY is generally a better choice than ##IDENTITY. In most cases, they will return the same value. But, for example, if your INSERT statement causes a trigger to fire, which inserts an identity value in a second table, then it's the identity value inserted into this second table that will be returned by ##IDENTITY. Using SCOPE_IDENTITY avoids this problem.

why is my insert not inserting a record in database

I am trying to insert a record into the database using the below method. I am calling this method in a button click event but for some reasons no record is being inserted.
There are four fields which need to be inserted: rpttemplateid - I am getting that field from another database table and all the other feilds are just static values.
What am i doing wrong below?
public void updatereporttemplate()
{
string cnn = WebConfigurationManager.ConnectionStrings["Underwriting"].ConnectionString;
SqlConnection cnn1 = new SqlConnection(cnn);
cnn1.Open();
string getrptdesc = "select max(rptdesc) + 1 from report_description where rptdesc < 999 and rptdesc is not null";
SqlCommand cmd = new SqlCommand(getrptdesc, cnn1);
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
int getcount = int.Parse(sdr[0].ToString());
sdr.Close();
string commandtext1 = "INSERT INTO report_template" + "(rpttemplateid,rpttemplatedescr,minsubs,minmebers) " +
" Values( " + getcount + "," + " " + " , " + 0 + "," + 0 + ")";
SqlCommand command1 = new SqlCommand
{
CommandText = commandtext1,
Connection = cnn1
};
You are missing command1.ExecuteNonQuery();
Also, have you considered using an IDENTITY column in your table instead of trying to manually set the count? What if that page is hit by multiple people at the same time?
You need to open the connection
cnn1.Open();
And then execute the command
command1.ExecuteNonQuery();

ASP.net Gridview does not display first row

SqlDataReader myReader1 = null;
SqlCommand myCommand1 = new SqlCommand("SELECT Standard_Note_Code, COUNT(Standard_Note_Code) as Count FROM [Excel_table] where Standard_Note_Creator_Name = '" + ddlrep.Text + "' and (Std_Note_Date_Entered >= '" + datefrom + "' and Std_Note_Date_Entered <= '" + dateto + "') group by Standard_Note_Code", myConnection);
myReader1 = myCommand1.ExecuteReader();
myReader1.Read();
gvsummary.Visible = true;
if (myReader1.HasRows)
{
gvsummary.DataSource = myReader1;
gvsummary.DataBind();
}
else
{
myReader1.Close();
//myConnection.Close();
//Label2.Text = "No Records Exist";
}
myReader1.Close();
Remove myReader1.Read();, after ExecuteReader. That line causes the grid to start reading from the 2nd position.
Everything looks correct to me, except I don't think you should be calling
myReader1.Read();
before you bind to the GridView. I think if you remove that line it will fix your problem.
Don't call myReader1.Read(); if you're binding as a data source.

DataReader already open error when trying to run two queries

I have a couple of queries that I need to run one to a linked server and one not like this
Dim InvestorLookup As String = "DECLARE #investor varchar(10), #linkedserver varchar(25), #sql varchar(1000) "
InvestorLookup += "SELECT #investor = '" & investor & "', #linkedserver = '" & db & "', "
InvestorLookup += "#sql = 'SELECT * FROM OPENQUERY(' +#linkedserver + ', ''SELECT * FROM db WHERE investor = ' + #investor + ' '')' EXEC(#sql)"
Dim queryInvestorLookup As SqlCommand = New SqlCommand(InvestorLookup , conn)
Dim BondNoDR As SqlDataReader = queryInvestorLookup.ExecuteReader()
Dim PasswordCheck As String = "DECLARE #investor varchar(10), #password varchar(20), #linkedserver varchar(25), #sql varchar(1000) "
PasswordCheck += "SELECT #investor = '" + investor + "', #password = '" + password + "', #server = '" + db2 + "', "
PasswordCheck += "#sql = 'SELECT * FROM #server WHERE investor = #investor AND password = ' + #password + ' '' EXEC(#sql)"
Dim queryPasswordCheck As SqlCommand = New SqlCommand(PasswordCheck, conn)
Dim PasswordDR As SqlDataReader = queryPasswordCheck.ExecuteReader()
As far as I can tell from debugging the queries both run as they should but I get the error
There is already an open DataReader associated with this Command which must be closed first.
Is it possible to run two queries in two different DataReaders. I need to later reference each DataReader and select values from each.
By default it´s not possible to have two SqlDataReader's open at the same time sharing the same SqlConnection object. You should close the first one (queryInvestorLookup) before calling the second (queryPasswordCheck).
This would be good from a design and performance point of view since a recommendation for .NET is that every unmanaged resource (like database access) is opened as later as possible and closed early as possible.
Another way would be to enable MARS but afaik it is only available for Sql2005 and up.
The third solution would be to use the same SqlDataReader to issue the two queries and then navigate through then using NextResults() method.
If the provider that you are using supports it, you can enable MARS (Multiple Active Result Sets) by adding MultipleActiveResultSets=True to the connection string that you are using.
By default you can't have to dataReaders open on the same connection. So you could get one result, stuff it in a DataTable and then get the other result. Or you could turn on MARS
ADO.NET Multiple Active Resut Sets

Resources