I have access to a stored procedure on a sql server which has one parameter and I can easily run it on the sql client as follow:
exec sp_name "2016/11/01"
Now I want to do the same thing in java.
PreparedStatement ps = conn.prepareStatement("sp_name ?");
ps.setString(1, "2016/11/01");
ResultSet rs = ps.executeQuery();
In rs I can see the columns' names, but zero row is returned. I think it is because of the stored procedure's parameter. Am I missing something here?
Here is the code that worked eventually:
String date= "2016/11/01"
String queryString "exec sp_dmp_pub_status ?";
PreparedStatement ps = conn.prepareStatement(queryString);
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date parsed = format.parse(date);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
ps.setDate(1, sqlDate);
ResultSet rs = ps.executeQuery();
Related
i want to sum the values of a column where date is today's date and pass it to a variable. i wrote the following code but it's not working.
error: "column name sum(Bill_Total) not valid." its considering "sum(Bill_Total)" as a column.
String sql = "select sum(Bill_Total) from t_report where date=?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setDate(1, date);
ResultSet rs = pst.executeQuery();
String sum=rs.getString(sql);
can someone tell me whats wrong with my query. thanks in advance
Is it me or the error is when you're fetching the result?
String sql = "select sum(Bill_Total) as bill_total from t_report where date=?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setDate(1, date);
ResultSet rs = pst.executeQuery();
String sum=rs.getString("bill_total");
Try this:
SELECT SUM(Bill_Total) AS `Bill_Total`
FROM t_report
WHERE date=?
I am trying to write a query and get results from oracle db using java and jdbc. My problem is the same query works if I try with statement, but the same query does not work if I use preparedStatement.
Statement Code: (Here I get real count value)
Statement stmt = con.createStatement();
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate + "','YYYY-MM-DD')";
rs = stmt.executeQuery(sql);
PreparedStatement Code: (Here I get count value zero)
Date sqlDate = new java.sql.Date(someJava.Util.Date.getTime());// = 2015-09-24
sqlString = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE(?,'YYYY-MM-DD')";
pstmt = con.prepareStatement(sqlString);
pstmt.setDate(1, sqlDate);
rs = pstmt.executeQuery();
When I sysout my sqlDate prints like: 2015-09-24.
I have same problem with some other queries.
Can anyone know whats wrong here?
The TO_DATE function converts a string to a date given a certain format. So the parameter passed to the prepared statement should be the String to be converted by the Oracle function:
pstmt.setString(1, sqlDate.toString());
Or you can change the query so that the parameter is the date itself and pass the java.sql.Date object to the prepared statement:
sqlString = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = ?";
pstmt.setDate(1, sqlDate());
Note that, for the normal statement query:
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate + "','YYYY-MM-DD')";
the String concatenation will append the string representation of the object, i.e. it is equivalent to:
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate.toString() + "','YYYY-MM-DD')";
i am passing date in sql query using java.Below is my code that retrieve no result.
java.sql.Date d1=java.sql.Date.valueOf(startDate);
java.sql.Date d2=java.sql.Date.valueOf(enddate);
String url= "jdbc:jtds:sqlserver://"+serverName+"/"+database;;
String driver = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
System.out.println("Connected to the database!!! Getting table list...");
Statement sta = conn.createStatement();
String Sql = "Select INDEX from Table where DATE between "+d1+" and "+d2;
System.out.println("sql="+Sql);
rs = sta.executeQuery(Sql);
}
} catch (Exception e) {
e.printStackTrace();}
Query returns no row because date should be passed as '2015-02-28' but query treats date as 2015-02-28 without single quote.Please suggest.
Creating SQL statements by concatenating strings together makes your software vulnerable to SQL injection (if the values of the variables come from user input).
You should use PreparedStatement instead:
PreparedStatement sta =
conn.prepareStatement("Select INDEX from Table where DATE between ? and ?");
sta.setDate(1, d1);
sta.setDate(2, d2);
rs = sta.executeQuery(Sql);
Add single quotes
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2+"'";
but the best option would be using PreparedStatement.
Try it like so:
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2 + "'";
That being said, you should look into PreparedStatements.
You have multiple issues in the query
INDEX is a reserved word and you need to escape it using backticks http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Date should be used within quotes
So the query should be
String Sql = "Select `INDEX` from Table where DATE between '"+d1+"' and '"+d2+"'";
Replace Your Query with
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2+"'";
I suggest you to use PreparedStatement Instead
String query="Select INDEX from Table where DATE between ? and ?";
PreparedStatement ps=con.prepareStatement(query);
ps.setDate(1,d1);
ps.setDate(2,d2);
ps.executeQuery();
I have a PreparedStatement such as:
PreparedStatement preparedStatement = connect.prepareStatement("INSERT into employee (id, time, name" + "(?,?,?)",Statement.RETURN_GENERATED_KEYS);
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
preparedStatement.executeUpdate();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);
preparedStatement.setInt(1,autoGeneratedID);
preparedStatement.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(3, "Test");
preparedStatement.executeUpdate();
As you can see, the Employee table has an auto-incremented ID. I need to basically add it in automatically using preparedStatement as well. Can someone tell me where I am going wrong and correct me? Right now it just gives me an error related to Statement.
Leave the column out of the INSERT statement entirely. It will be generated by the database engine. Your query should be:
INSERT INTO employee (time, name)
VALUES (?, ?)
Secondly, you have to perform the insert first, then get the keys out of the result.
I believe your code should be:
PreparedStatement preparedStatement =
connect.prepareStatement("INSERT into employee (time, name) VALUES (?,?)",
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setTimestamp(1,
new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(2, "Test");
preparedStatement.executeUpdate();
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);
Note this example does not check the success of the executed statement or the existence of returned keys.
You should perform some modification(define default statement) to prepared statement string like this:
"INSERT into employee VALUES(default,?,?)"
That modification is because of occurring this problem : Column count doesn't match value count at row 1 JAVA mysql
After that you're code is something like below:
PreparedStatement preparedStatement =
connect.prepareStatement("INSERT into employee VALUES (default,?,?)", Statement.RETURN_GENERATED_KEYS);
preparedStatement.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime()));
preparedStatement.setString(2, "Test");
preparedStatement.executeUpdate();
ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
Thanks to Ic. for his answer.
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","password");
PreparedStatement ps = con.prepareStatement("insert into imgslider(id,cmnt,date1,img,status) values(seq.nextval,?,?,?,?)");
ResultSet rs = null;
String s1 = "I’ve Come and I’m Gone: A Tribute to Istanbul’s Street";
ps.setString(1,s1);
Calendar calendar = Calendar.getInstance();
java.sql.Date dd = new java.sql.Date(calendar.getTime().getTime());
ps.setDate(2,dd);
FileInputStream f1 = new FileInputStream("F:\\java\\slide-9.jpg");
ps.setBinaryStream(3,f1,f1.available());
ps.setInt(4,0);
int i = ps.executeUpdate();
System.out.println(i+" rows affected");
con.close();
}
here is my code for auto-increment column in table by PreparedStatement.
How can I Convert Java Timestamp (Timestamp data type) to MySQL timestamp vice versa?
If you're using the JDBC API to access the database, and you're using a PreparedStatement to for example execute an SQL INSERT statement, then you just set the timestamp as a parameter to the PreparedStatement:
Timestamp ts = ...; // wherever you get this from
PreparedStatement ps = connection.prepareStatement("INSERT INTO MYTABLE (ts) VALUES (?)");
ps.setTimestamp(1, ts);
ps.executeUpdate();
Likewise, when you're doing a query that returns a timestamp, get it from the ResultSet by calling getTimestamp on it. Example:
Timestamp result = null;
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT ts FROM MYTABLE WHERE ...");
if (rs.next()) {
result = rs.getTimestamp(1);
}
See the JDBC Tutorial.
Without more specifics on the trouble you are having, this will be a hard question to answer. However, Java makes this relatively straightforward if you are using prepared statements. Your code would look something like this:
Connection conn = getConnection();
PreparedStatement pStmt = conn.prepareStatement("UPDATE my_table SET my_column = ? WHERE id = ?");
pStmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
pStmt.setInt(2, 42);
pStmt.executeUpdate();
As far as I can see from MySQL docs, java.sql.Timestamp should just work if you read it from or write it to a TIMESTAMP field in the database. So you should not need to do any conversion.