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';
Related
I am trying to fetch data from postgres database using where clause. It is returning null values. But running the same query in postgres worksheet, it is giving the datas.
And one more thing, I cannot able to use without double quotes(\"USER_INFO\"),while using without double quotes I am getting the error "column name does not exist".
But most of the online examples are without double quotes only.
Please help on this to resolve. Thanks in advance.
public class PostGreDB {
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:5432/";
public static void main(String[] args) throws SQLException
{
Connection conn = null;
//Statement st = null;
try{
//STEP 2: Register JDBC driver
Class.forName("org.postgresql.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","postgres","XXXX#1904");
//STEP 4: Execute a query
System.out.println("Creating statement...");
//st = conn.createStatement();
String sql;
sql = "SELECT * FROM public." + "\"USER_INFO\" where \"USER_INFO\".\"EMAIL_ID\" = ?";
System.out.println(sql);
try(PreparedStatement pst= conn.prepareStatement(sql)){
pst.setString(1 , "cppandi33#gmail.com");
pst.executeQuery();
try(ResultSet rs = pst.getResultSet()){
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String first = rs.getString("USER_ID");
String last = rs.getString("USER_NAME");
String email = rs.getString("EMAIL_ID");
//Display values
System.out.print("User ID: " + first+"\n");
System.out.println("User Name: " + last+"\n");
System.out.println("Email: " + email);
}
rs.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//STEP 6: Clean-up environment
// st.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally
{
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}
}
}
When column contains "null" as data. It gives null only. Try to insert some data using insert query and after that we can try to fetch.
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
I want to have to use the users input for driverID, change onJob to true, if the user inputs the id.
So for example, if the user enters 1 as the driver id, the driver with id number 1 will have the onJob variable change to 1.
Here is my code currently;
public class TaxiDriver {
//String driverLocation = DRIVERFIRSTLOCATION;
//String destinationintoAPI;
//JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/DRIVER";
//Database credentials
static final String USER = "user";
static final String PASS = "password";
String driverId;
static Scanner reader = new Scanner(System.in);
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 a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Assign a driver to a jo...");
reader.nextInt();
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE Drivers " +
"SET OnJob = 1 WHERE id = (driverId)";
stmt.executeUpdate(sql);
// Now you can extract all the records
// to see the updated records
sql = "SELECT id, license, first, last, OnJob, Email, Telephone, Address, Postcode, Veichle FROM Drivers";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
//retrieve by column name
int id = rs.getInt("id");
int license = rs.getInt("license");
String first = rs.getString("first");
String last = rs.getString("last");
int OnJob = rs.getInt("OnJob");
String Email = rs.getString("Email");
String Telephone = rs.getString("Telephone");
String Address = rs.getString("Address");
String Postcode = rs.getString("Postcode");
String Veichle = rs.getString("Veichle");
//Display
System.out.print("ID: " + id);
System.out.print(", license: " + license);
System.out.print(", First: " + first);
System.out.print(", Last: " + last);
System.out.print(", Email; " + Email);
System.out.print(", Telephone; " + Telephone);
System.out.print(", Address; " + Address);
System.out.print(", Postcode; " + Postcode);
System.out.print(", Veichle;" + Veichle);
if (OnJob == 0) {
System.out.println(": Driver is aviliable for pickup");
} else {
System.out.println(": Driver is not aviliable for pickup");
}
}
rs.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)
conn.close();
} catch (SQLException se) {
}// do nothing
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
Right now I am getting these errors.
Connecting to a selected database...
Tue May 03 00:18:28 BST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended.
According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set.
For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'.
You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Connected database successfully...
Assign a driver to a jo...
2
Creating statement...
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'driverId' in 'where clause'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1541)
at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2605)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1469)
at TaxiDriver.main(TaxiDriver.java:71)
Goodbye!
Much thanks in advance.
First, you actually need to read in a value into driverId somewhere.
That aside, the problem is with your SQL statement. You have:
String sql = "UPDATE Drivers " +
"SET OnJob = 1 WHERE id = (driverId)";
You are telling the database to look for records where the value of the records' id column equals the value of their driverId column.
You need to get the value of your driverId variable into the SQL rather than putting the actual characters "driverId" into the SQL, where (as you see) it is interpreted as the name of a column.
Using your approach you need to do:
String sql = "UPDATE drivers SET OnJob=1 WHERE id=" + driverId;
But dynamic SQL is dangerous and you are better off using a PreparedStatement. That will sanitize the user inputs and prevent SQL injection attacks.
String sql = "UPDATE drivers SET OnJob=1 WHERE id=?";
PreparedStatement ps = connection.createPreparedStatement(sql);
ps.setInt(1, Integer.parseInt(driverId));
ResultSet rs = ps.executeQuery();
You don't seem to be setting the driverId from user input.
Update your sql statement with valid id value, before executing the script.
i.e.
int driverId = 123;// This is user input, am assuming its type int.
String sql = "UPDATE Drivers SET OnJob = 1 WHERE id =" + driverId;
//now execute your sql
String driverId = "123";//This is user input, am assuming its type String.
String sql = "UPDATE Drivers SET OnJob = 1 WHERE id =" + "'" + driverId + "'";
//now execute your sql
Edit: I highly recommend QuantumMechanic's solution of using PreparedStatement as its much safer and hides all the handling of different types.
i wanted to connect to mysql from java code where mysql is in another system.
i have created a user in another machine "nilotpal".
Other machine address is 192.168.92.93.
I am able to ping to this machine. where am i missing?? can someone help?!!
The program i am using is:
import java.sql.*;
public class FirstExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://192.168.92.93:3306/tution";
// Database credentials
static final String USER = "nilotpal";
static final String PASS = "nilotpal";
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, first, last, age FROM Employees";
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("first");
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
Reference from Connect to mysql on a different server
Also make sure that mysql user nilotpal have remote connection permission. Other wise mysql-server will not allow your nilotpal user to login remotely. i.e. from your server (from program).
You can make sure that from mysql.user table.
mysql> select Host,User from user where User = "root";
+------------+------+
| Host | User |
+------------+------+
| 127.0.0.1 | root |
| ::1 | root |
| localhost | root |
| sgeorge-mn | root |
| % | root |
+------------+------+
4 rows in set (0.01 sec)
% means any host.
To create a user with remote connection permission, use following mysql query:
mysql> CREATE USER 'nilotpal'#'%' IDENTIFIED BY 'nilotpal';
First ping the machine using ping command, If it is pinging than check for the mysql user permission.
Granting Permission to user:
CREATE USER 'newuser'#'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'#'localhost';
FLUSH PRIVILEGES;
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