jsp insert time in database - database

PreparedStatement pstmt = conn.prepareStatement(
"INSERT INTO discussion(section_id, weekday, room, mandatory, starttime,endtime)
VALUES ( ?, ?, ?, ?, ?, ?)");
pstmt.setInt(1, Integer.parseInt(request.getParameter("SECTION_ID")));
pstmt.setString(2, request.getParameter("WEEKDAY"));
pstmt.setString(3, request.getParameter("ROOM"));
pstmt.setString(4, request.getParameter("MANDATORY"));
pstmt.setString(5, request.getParameter("starttime"));
pstmt.setString(6, request.getParameter("endtime"));
right now I set the starttime and endtime in database as time without timezone type
if I use setTime to get the endtime and startime. how to modify this code
I didn't use any class here. I don't think I can use method here
the data is from user input

Suppose your dateString intered by user is in format dd-MMM-yyyy HH:mm:ss
Then you can use setDate like this
private static final String TIME_FORMAT = "HH:mm:ss";
public static final SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
pstmt.setTime(5,new Time(timeFormat.parse(request.getParameter("starttime")).getTime()));
Hope this will help

1.you should this method:
PreparedStatement pstmt;
pstmt = con.prepareStatement("INSERT INTO table_name (starttime,endtime)VALUES(?,?)");
pstmt.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime));
pstmt.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime));
pstmt.executeUpdate();
sample:
PreparedStatement pstmt;
pstmt = con.prepareStatement("INSERT INTO table_name (col_name)VALUES(?)");
pstmt.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime));
pstmt.executeUpdate();
2.Another one interesting answer:
You can use SimpleDateFormat to parse a String in the given pattern to a java.util.Date object.
Assuming that it's HH:mm, then you can do so:
String time = request.getParameter("time");
Date date = null;
try
{
date = new SimpleDateFormat("HH:mm").parse(time);
}
catch (ParseException e)
{
request.setAttribute("time_error", "Please enter time in format HH:mm");
}
Once having the java.util.Date object, you can store it in a TIME column by converting it to java.sql.Time and using PreparedStatement#setTime().
PreparedStatement pt;
pt = connection.prepareStatement("INSERT INTO tablename (columname) VALUES (?)");
pt.setTime(1, new Time(date.getTime()));
pt.executeUpdate();

Related

getparameter return null jsp when get time like 9:00

PreparedStatement pstmt = conn
.prepareStatement("INSERT INTO discussion(section_id, weekday, room, mandatory, starttime,endtime) VALUES ( ?, ?, ?, ?, ?, ?)");
pstmt.setInt(1, Integer.parseInt(request.getParameter("SECTION_ID")));
pstmt.setString(2, request.getParameter("WEEKDAY"));
pstmt.setString(3, request.getParameter("ROOM"));
pstmt.setString(4, request.getParameter("MANDATORY"));
String TIME_FORMAT = "HH:mm";
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT,
Locale.getDefault());
out.println("Items: " + request.getParameter("starttime"));
out.println("Items: " + request.getParameter("WEEKDAY"));
pstmt.setTime(5,
new Time(timeFormat.parse(request.getParameter("starttime"))
.getTime()));
pstmt.setTime(6,
new Time(timeFormat.parse(request.getParameter("endtime"))
.getTime()));
pstmt.executeUpdate();
I use out.print to test. find out that getparameter works not right. It can give me the weekday data but cannot give me starttime data. The database give starttime time type

How can I convert a date to this particular string representation?

LblExpirydate.Text = dataReader(0).ToString()
Output in asp.net form : 01/05/2013 12:00:00 AM
I want to change format to (01/05/2013)
Notes : My database
Column : Expirydate
data type : Date
You can format the string using .ToString() in several different ways:
dataReader(0).ToString("dd/MM/yyyy");
dataReader(0).ToString("d");
The second option is better as it will format using the current locale. See this MSDN article for more info:
http://msdn.microsoft.com/en-gb/library/az4se3k1.aspx
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MM/dd/yyyy") ;
output:
03/30/2013
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MM-dd-yyyy") ;
output:
03-30-2013
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MM,dd,yyyy") ;
output:
03,30,2013
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MMMM,dd,yyyy") ;
output:
March,30,2013
and so on...

sql server date in the format yyyy-MM-ddThh:mm:ssZ

I need to format a set of dates in SQL server to the following format..
yyyy-MM-ddThh:mm:ssZ
I cant seem to find how to format the date with the T and Z parts included in the string
Any ideas how to achieve this format in a SQL query?
According to the SQL Server 2005 books online page on Cast and Convert you use date format 127 - as per the example below
CONVERT(varchar(50), DateValueField, 127)
SQL Server 2000 documentation makes no reference to this format - perhaps it is only available from versions 2005 and up.
Note on the time zone added to the end (from note 7 in the docs): The optional time zone indicator, Z, is used to make it easier to map XML datetime values that have time zone information to SQL Server datetime values that have no time zone. Z is the indicator for time zone UTC-0. Other time zones are indicated with HH:MM offset in the + or - direction. For example: 2006-12-12T23:45:12-08:00.
Thanks to Martin for this note: You should be able to use STUFF to remove the miliseconds as these will be in a fixed position from the left of the string. i.e.
SELECT STUFF(CONVERT(VARCHAR(50),GETDATE(), 127) ,20,4,'')
DECLARE #SampleDate DATETIME2(3) = '2020-07-05 23:59:59';
SELECT CONVERT(VARCHAR(20), CONVERT(DATETIMEOFFSET, #SampleDate), 127);
--results: 2020-07-05T23:59:59Z
You can parse C# output in SQL using below:
SELECT CONVERT(DATETIME, CONVERT(DATETIMEOFFSET,'2017-10-27T10:44:46Z'))
Use C# to generate this using the following:
string ConnectionString = "Data Source=SERVERNAME; Initial Catalog=DATABASENAME; Persist Security Info=True; User ID=USERNAME; Password=PASSWORD";
using(SqlConnection conn = new SqlConnection(ConnectionString))
{
DateTime d = DateTime.Now;
string Query = "SELECT CONVERT(DATETIME, CONVERT(DATETIMEOFFSET,'" + d.ToString("yyyy-MM-dd") + "T" + d.ToString("HH:mm:ss") + "Z'))"
conn.Open();
using(SqlCommand cmd = new SqlCommand(Query, conn))
{
using(SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.HasRows)
{
while(rdr.Read())
{
for(int i; i < rdr.length; i++)
{
Console.WriteLine(rdr[0].ToString());
}
}
//DataTable dt = new DataTable(); dt.Load(rdr); //Alternative method if DataTable preferred
}
}
}
}
select left(convert(varchar(30),getdate(),126)+ '.000',23)
Try this
SELECT STUFF(
CONVERT(datetime2(0), GETDATE(), 126)
AT TIME ZONE 'US Eastern Standard Time'
,11,1,'T')
on MSSQL
SELECT FORMAT( GETDATE(),'yyyy-MM-ddTHH:mm:ss.ms zzzz')

How to save byte[] using a procedure?

This stored procedure does not save the data, it seems to be a problem with the VARBINARY. I am passing a byte[] to it, but then it doesn't work. If I send this parameter as NULL it works.
I'm calling the procedure with the following code:
public Community AddCommunity(string name, string description, byte[] picture, User owner, int? venue, int communityID)
{
using (var database = new Database())
{
return database.Scope.GetSqlQuery<Community>("QP_AddCommunity ?, ?, ?, ?, ?, ?", "VARCHAR Name, VARCHAR Description, VARBINARY Picture, INTEGER Owner, INTEGER Venue, INTEGER ID").GetResult(name, description, picture, owner.ID, venue, communityID);
}
}
The procedure is the following:
CREATE PROCEDURE [dbo].[QP_AddCommunity]
#Name VARCHAR(120),
#Description VARCHAR(MAX),
#Picture VARBINARY(MAX),
#Owner INTEGER,
#Venue INTEGER,
#ID INTEGER
AS
BEGIN
SET NOCOUNT ON;
IF(SELECT COUNT(*) FROM QT_Community WHERE ID = #ID) = 0
INSERT INTO QT_Community(Name, [Description], Picture, [Owner], Venue) VALUES(#Name, #Description, #Picture, #Owner, #Venue);
ELSE
UPDATE QT_Community SET Name = #Name, [Description] = #Description, Picture = #Picture, [Owner] = #Owner, Venue = #Venue WHERE ID = #ID;
SELECT * FROM QT_Community WHERE ID = ##IDENTITY;
END
What's wrong with this code? Isn't VARBINARY a byte[] ?
This code works when executing on SQL Server Management Studio.
DECLARE #X varbinary(20)
Set #X = CAST('Testing' As varbinary(20))
EXECUTE [QP_AddCommunity] 'aaaaa', 'descricao', #X, 216, NULL, 0;
But when calling from the GetSqlQuery method with something on the byte[] the transaction says it's not active and not dirty. BUT if the byte[] is null it works as it should.
i found that it is impossible as this answer shows
Hello gaurav, currently our
GetSqlQuery method cannot operate
properly with parameters of type
LongVarBinary or VarBinary, thus
making it impossible for the stored
procedure to work as expected. We are
aware of this problem and we are
working on fixing it. As a work around
you should try and use Linq to achieve
your goal. Greetings, Petar the
Telerik team
Accordingly to this table it seems either BLOB, BINARY, VARBINARY would be valid types for [] of primitive type.
You could try to ask on their forums, maybe someone will be able to help you.
Try using the .WRITE method. On your INSERT, insert 0x for Picture, then update independently.
UPDATE QT_Community
SET Picture.Write (#Picture, 0, DATALENGTH(Picture))
WHERE ID = #ID
Example (Ado.Net):
byte[] ba = UlongsToBytes(ul);
try
{
string source = #"packet size=4096;integrated security=SSPI;data source=MyPC\MyNamedInstance;persist security info=False;initial catalog=Sandbox";
SqlConnection conn = new SqlConnection(source);
conn.Open();
SqlCommand a = new SqlCommand("INSERT BigintsTarget(bi) SELECT * FROM dbo.ParseImageIntoBIGINTs(#BIGINTs)", conn);
a.CommandType = System.Data.CommandType.Text;
a.Parameters.Add(new SqlParameter("#BIGINTs", System.Data.SqlDbType.Image,2147483647));
for(int q=0; q<10; q++)
{
a.Parameters[0].Value = ba;
int res = a.ExecuteNonQuery();
}
d2 = DateTime.Now;
SqlCommand b = new SqlCommand("INSERT BigintsTarget1(bi) SELECT * FROM dbo.ParseVarcharMAXIntoBIGINTs(#BIGINTs)", conn);
b.CommandType = System.Data.CommandType.Text;
b.Parameters.Add(new SqlParameter("#BIGINTs", System.Data.SqlDbType.VarChar,2147483647));
for(int q=0; q<10; q++)
{
b.Parameters[0].Value = sss;
int res = b.ExecuteNonQuery();
}
//b.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
string s = ex.Message;
int t=0;
t++;
}
}

JDBC - prepareStatement - How should I use it?

I saw this example somewhere:
rs = connection.prepareStatement("select * from table").executeQuery();
Could I use this format, if I want to execute a query like this "Select * from table where column = "hello" "?
The way in which I usual I use prepareStatement object is something like this:
String sql = "select * from adresa where column = ?";
PreparedStatement pre = con.prepareStatement(sql);
pre.setString(1, i);
rs = pre.executeQuery();
Later Edit:
I don't understand. Pascal Thivent wrote that I can use the short version with In parameters, but Liu tells me this is not possible. :) Anw, using Pascal's version, i receive this error: void cannot be dereferenced
Here's a partial example how to use this interface:
static final String USER = "root";
static final String PASS = "newpass";
Connection conn = DriverManager.getConnection(myUrl, USER, PASS);
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into students (ID, last_name, first_name, birthday, hometown)"
+ " values (?, ?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, 808027);
preparedStmt.setString(2, "Davis");
preparedStmt.setString(3, "Felicita");
preparedStmt.setDate(4, startDate);
preparedStmt.setString(5, "Venice");
// execute the preparedstatement
preparedStmt.execute();
conn.close();
You can only use the first form if there are no bind variables (question marks) in the query. It's just a shortened version of what you posted.
Also, if you use the shortened form you won't have the opportunity to reuse the PreparedStatement object.
of course u can use a string variable for the query in which u put in ur dynamic data and run it.
rs = connection.prepareStatement(variable).executeQuery();
The long form is often, but prepared statements can be precompiled by the db, and if used properly will help prevent sql injection.
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
conn = getConn();
ps = conn.prepareStatement("select * from x where y = ? "); //note no sb.append()'s or +'s, to helps prevent sql injection
ps.setLong(1, 12l);
rs = ps.executeQuery();
while (rs.next()) {
... act ...
}
} catch ( Exception e) {
} finally {
if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();
}
Who said java was verbose. :)

Resources