getting out parameter from mysql stored procedure in java - java

I am having problem retrieving OUT parameter from mysql stored procedure in java.
CALL proc_after_topic_add('newtest',#result);
SELECT #result;
this query gives me desired out parameter but how would i retrieve it in java.I tried using CallableStatement but i get
java.sql.SQLException: Callable statments not supported.
error.Please guys help me.
I have tried following
String sql = "CALL proc_after_topic_add(?,?);";
CallableStatement cstmt = conn.prepareCall(sql);
cstmt.setString(1, topicname);
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
ResultSet rs = cstmt.executeQuery();
if (rs.next()) {
if (rs.getInt(1) == 1) {
res = 0;
} else {
res = -1;
}
}
I havent posted stored procedure code because there is nothing wrong with it.
PS:I a using mysql 5.5.21 and yes i should probably mention i am using mysql connector 3.0.15
Okay this is solved.For anyone who encounters the same problem,just download latest version of mysql connector.

Error in this line
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
change like this
String sql = "CALL proc_after_topic_add(?,?);";
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);

Create a schema test and create a table employee in schema with 2 columns.
id and employeename and insert some data.
Use this Stored Procedure.
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`get_count_name1` $$
CREATE PROCEDURE `test`.`get_count_name1`(IN the_name VARCHAR(64),OUT
the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count from employee where employeename=the_name;
END$$
DELIMITER ;
Use this example.
username and password are root and root for me. change as per your
requirement. Here i am counting the occurence of employeename="deepak"
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
CallableStatement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "{call get_count_name1 (?, ?)}";
stmt = conn.prepareCall(sql);
//Bind IN parameter first, then bind OUT parameter
String name = "Deepak";
stmt.setString(1, name); // This would set ID as 102
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.INTEGER);
//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();
int count=stmt.getInt(2);
System.out.println(count);
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample

Related

How do I list multiple databases with their tables by using "Show Tables" via Java?

I am trying to list MySQL databases and their tables with Java. For now, I have two databases as "Database_Services with MySQL_Database_Service, MSSQL_Database_Service, and Directory_Services with Active_Directory, OpenLDAP tables. I get the output for Database_Services and its tables but I do not get the other ones.
public class connectMySQL implements serverConnection{
Connection conn;
Statement stmt;
public void connect(String dbName){
String url;
try {
if(dbName.equals("")){
url = "jdbc:mysql://x:x/";
}
else{
url = "jdbc:mysql://x:x”+ dbName;
}
String username = “x”;
String password = "x";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
}
catch (SQLException ex)
{
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}
public class listInf extends connectMySQL implements listInfrastructure {
public void list() {
String dbName;
ResultSet rs;
try{
connect("");
String str = "SHOW DATABASES";
ResultSet resultSet = stmt.executeQuery(str);
while(resultSet.next()){
dbName = resultSet.getString("Database");
if(!dbName.contains("schema") && !dbName.equals("mysql")){
System.out.println(dbName);
rs = stmt.executeQuery("SHOW TABLES IN " + dbName);
while (rs.next()) {
System.out.println("\t" + rs.getString("Tables_in_" + dbName));
}
}
}
}
catch(SQLException e){
System.out.println("Error");
}
}
}
I want to get an output like:
Database_Services:
MySQL_Database_Service.
MSSQL_Database_Service.
Directory_Services:
Active_Directory_Service.
OpenLDAP_Service.
You are using the same Statement for multiple queries. You cannot do that. From the Javadoc of Statement:
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
Connection conn1 = DriverManager.getConnection(url, username, password);
Connection conn2 = DriverManager.getConnection(url, username, password);
Statement statement1 = conn1.createStatement();
Statement statement2 = conn2.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SHOW TABLES IN DB1");
ResultSet resultSet2 = statement2.executeQuery("SHOW TABLES IN DB2");
while (resultSet1.next()) {
System.out.println("");
}
while (resultSet2.next()) {
System.out.println("");
}
if you have more than 2 database, then simply you can use loop for to get the results.
You can use the meta information database information_schema.
SELECT
TABLE_SCHEMA,
TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA IN ('Database_Services', 'Directory_Services')
ORDER BY TABLE_SCHEMA

Can't Show database on XAMPP-> mysql to java

I am using XAMPP->Mysql to create database and using Netbeans IDE 8.1 fro create java
My Code
//default package
//1st step
import java.sql.*;
public class DemoJDBC {
public static void main(String[] args) {
try{
String Query = "Select * from Student";
//2nd step
Class.forName("com.mysql.jdbc.Driver");
//3rd step
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "0");
//4th step
Statement st = con.createStatement();
//5th step
ResultSet rs = st.executeQuery(Query);
rs.next();
String name = rs.getString("sname");
System.out.println(name);
//6th step
con.close();
}
catch (Exception e){
}
}
}
Why it didn't show output name ? It just show
"BUILD SUCCESSFUL (total time: 1 second)" in netbeans output
You need to loop through the ResultSet to get the tuples or rows. So while looping you retrieve whatever data or field you want to get. try:
public static void main(String[] args) {
try {
String Query = "Select * from Student";
//2nd step
Class.forName("com.mysql.jdbc.Driver");
//3rd step
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "0");
//4th step
Statement st = con.createStatement();
//5th step
ResultSet rs = st.executeQuery(Query);
//Loop to retrieve tuple(s) from the ResultSet rs
while (rs.next()) {
String name = rs.getString("sname");
System.out.println(name);
}
//6th step
con.close();
} catch (Exception e) {
}
}
NOTE if by default you did not change the password of the root user it is just the empty String (thus "" and not "0"). Other than that you know what you are doing.
Along with the correction of your code to loop through the ResultSet, you also need to correct your connection string as shown below:
Considering that your MySQL is running on the default MySQL port 3306 (which I see that you already are), the connection string needs to be updated.
Also saw that password for the user root is '0', is it really the password?
public static void main(String[] args) {
try {
String query = "SELECT * FROM Student";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "0");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
//Loop to retrieve tuple(s) from the ResultSet rs
while (rs.next()) {
String name = rs.getString("sname");
System.out.println(name);
}
con.close();
} catch (Exception e) {
}
}
Also ensure to have your MySQL Connector/J jar file to be present in your CLASSPATH to not to face any reference issues.
Hope that this helps!

copying table from one database to another(sybase to mysql) in java

I have written code to connect to sybase database and mysql database and copy one table from sybase database to mysql database. My program is working fine and i am getting done what i waned but not in sufficient time. Sybase has total around 10000 rows in table that i am copying and it is taking around 4 mins to copy.
Can you guys suggest any improvement that can decrease the copying time.
Following is my code:
package jdbcexmple;
import java.sql.*;
import java.util.*;
public class Jdbcexmple {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/alarm";
static final String JDBC_DRIVER_SECOND = "net.sourceforge.jtds.jdbc.Driver";
static final String DB_URL_SECOND = "jdbc:jtds:sybase://11.158.251.19:4100/fmdb";
static final String USER = "root";
static final String PASS = "abc";
static final String USER_SECOND = "your";
static final String PASS_SECOND = "xyz";
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String a;
String b;
String c;
String d;
Connection conn = null;
Connection conn_2 = null;
PreparedStatement stmt = null;
try{
Class.forName(JDBC_DRIVER);
System.out.println("connecting to database mysql");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("connected to database successfully");
Class.forName(JDBC_DRIVER_SECOND);
System.out.println("connecting to database SYBASE");
conn_2 = DriverManager.getConnection(DB_URL_SECOND, USER_SECOND, PASS_SECOND);
System.out.println("connected to database successfully");
System.out.println("creating table in given database");
String sql = "CREATE TABLE newtable (CSN VARCHAR(255), IsCleared VARCHAR(255), ID VARCHAR(255), IP VARCHAR(255), PRIMARY KEY ( ID ))";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
System.out.println("created table in database");
Statement stmt_1= conn_2.createStatement();
String sql_1 = "select tbl_alm_log_2000000000.Csn, tbl_alm_log_2000000000.IsCleared, tbl_alm_log_2000000000.Id From fmdb.dbo.tbl_alm_log_2000000000 Where IsCleared = 0";
ResultSet rs = stmt_1.executeQuery(sql_1);
//below loop is taking 4 mins ie copying
while (rs.next())
{
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
d = rs.getString(4);
sql = "INSERT INTO newtable values "+"("+"\""+a+"\","+"\""+b+"\","+"\""+c+"\","+"\""+d+"\""+")";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
System.out.println(a+" "+b+" "+c+" "+d);
}
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
conn_2.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
conn_2.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
Use Batch execution to insert data into mysql without execute one by one. You have already used PreparedStatement. That is fine.
There are two solutions:
Solution 1:-
String sql = "INSERT INTO newtable values (col1, col2,col3) values (?, ?, ?)";
Connection connection = new getConnection();
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement(sql);
final int batchSize = 1000;
int count = 0;
while (rs.next()){
ps.setString(1, rs.getString(1));
ps.setString(2, rs.getString(2));
ps.setString(3, rs.getString(3));
ps.addBatch();
if(++count % batchSize == 0) {
ps.executeBatch();
}
}
ps.executeBatch(); // insert remaining records
connection.commit();
ps.close();
connection.close();
Your insert will be fast further with transaction handling. (connection.setAutoCommit(false); and connection.commit();)
http://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html#addBatch--
http://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#executeBatch--
http://viralpatel.net/blogs/batch-insert-in-java-jdbc/
Solution 2:-
rewriteBatchedStatements can be set with DB_URL this way.
jdbc:mysql://localhost:3306/alarm?rewriteBatchedStatements=true
So here rewriting to data bulk insert. Table lock once and indexes update once. This is another fastest way.
You can turn on the caching or use a connection pool. Using this, the first connection call will create a cache which will save time to query database.
OracleDataSource ods = new OracleDataSource();
// set cache properties
java.util.Properties prop = new java.util.Properties();
prop.setProperty("MinLimit", "2");
prop.setProperty("MaxLimit", "10");
// set DataSource properties
String url = "jdbc:oracle:oci8:#";
ods.setURL(url);
ods.setUser("hr");
ods.setPassword("hr");
ods.setConnectionCachingEnabled(true); // be sure set to true
ods.setConnectionCacheProperties (prop);
ods.setConnectionCacheName("ImplicitCache01"); // this cache's name
// We need to create a connection to create the cache
Connection conn = ds.getConnection(user, pass);
Statement stmt = conn1.createStatement();
ResultSet rset = stmt.executeQuery("select user from dual");
conn1.close();
ods.close();
For more information, check the implicit connection caching on: http://docs.oracle.com/cd/B19306_01/java.102/b14355/concache.htm#CACFIJJB

How to get Row count for sql select query taht not return any record and add that in ArraryList

I have one problem that in my java programme when i select some record from database,i need records which are not retrun by sql query from database.
suppose i have 5 record in my table and i give 8 record in where condition in my java programme so i need 3 record in ArrayList for that programme did not retrun any values..
My sample programme is as below:-
import java.sql.*;
import java.util.ArrayList;
public class database {
static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
static final String DB_URL = "jdbc:oracle:thin:#localhost:1521:orcl";
static final String USER = "asiftest";
static final String PASS = "asif";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
ArrayList ar =new ArrayList();
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT contractno FROM temp_survival where contractno in ('77777','11111','22222','33333','44444','55555','66666','77777','363636','25252')";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String first = rs.getString("contractno");
System.out.print("contractno: " + first);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
For the above programme i am getting values for '77777','11111','22222','33333','44444','55555','66666','77777' but for next 2 records '363636','25252' i am are not getting values because that is not available in database table so i need to add them in arraylist in above proramme. Please help me
Make a List for input contact numbers (which you are passing in where clause)
Make a List of contact numbers which you are getting in the query results
Use CollectionUtils.substract(list1, list2)

How to remove this bug while making jdbc simple program

Hi
I am making simple program of getting data from data base .I download sql for mac and insert schema , then table and entry .So I need to retrieve data from data base .I am using mysql .
I also insert conector jar of mysql .
I do like that
import java.sql.*;
![public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Database";
// Database credentials
static final String USER = "";
static final String PASS = "";
public static void main(String\[\] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM Employee";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("name");
// String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
// System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample][3]
Connecting to database...
Goodbye!
java.sql.SQLException: null, message from server: "Host '192.168.1.100' is not allowed to connect to this MySQL server"
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1086)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1114)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2493)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2311)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:347)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at FirstExample.main(FirstExample.java:21)
Your DB user is not allowed to connect to your MySQL server. In MySQL (strangely) there is something like a firewall and access is defined per user per host. You need to connect to MySQL via any SQL client and give access:
http://dev.mysql.com/doc/refman/5.1/en/adding-users.html
For example a bit too broad access but should work:
GRANT ALL PRIVILEGES ON *.* TO 'monty'#'%' WITH GRANT OPTION;
If you didn't create a user first:
CREATE USER 'monty'#'localhost' IDENTIFIED BY 'some_pass';

Categories

Resources