I need to export a table from mysql using java. I tried using
public class automateExport {
public static void main(String[] argv) throws Exception {
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
String serverName = "192.168.0.189";
String mydatabase = "ArchiveIndexer";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "username";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
String filename = "c:/outfiless.txt";
String tablename = "D_Centre";
System.err.println("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
stmt.executeUpdate("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
// stmt.executeQuery("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
// stmt.execute("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
}
}
But this is throwing error like
"Exception in thread "main" java.sql.SQLException: Can not issue SELECT via executeUpdate().
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1764)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1725)
at automateexceldatabase.automateExport.main(automateExport.java:38)
Java Result: 1"
This will help:
public class DatabaseToCSV {
public static void main(String[] args) {
String filename =
"C:\\Documents and Settings\\admin\\My Documents\\NetBeansProjects\\AutomateExcelDatabase\\myjdbcfile.csv";
try {
FileWriter fw = new FileWriter(filename);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(
"jdbc:mysql://192.168.0.189:3306/ArchiveIndexer"
, "username"
, "password"
);
String query = "select * from D_Centre";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append(',');
fw.append(rs.getString(4));
fw.append('\n');
}
fw.flush();
fw.close();
conn.close();
System.out.println("CSV File is created successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
this might help u : Export database to csv file
Example below exports data from MySQL Select query to CSV file.
testtable structure
CREATE TABLE testtable
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
text varchar(45) NOT NULL,
price integer not null);
Application takes path of output file as an argument.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class automateExport {
public static void main(String[] args) {
DBase db = new DBase();
Connection conn = db.connect(
"jdbc:mysql://localhost:3306/test","root","caspian");
if (args.length != 1) {
System.out.println(
"Usage: java automateExport [outputfile path] ");
return;
}
db.exportData(conn,args[0]);
}
}
class DBase {
public DBase() {
}
public Connection connect(String db_connect_str,
String db_userid, String db_password) {
Connection conn;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(db_connect_str,
db_userid, db_password);
} catch(Exception e) {
e.printStackTrace();
conn = null;
}
return conn;
}
public void exportData(Connection conn,String filename) {
Statement stmt;
String query;
try {
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//For comma separated file
query = "SELECT id,text,price into OUTFILE '"+filename+
"' FIELDS TERMINATED BY ',' FROM testtable t";
stmt.executeQuery(query);
} catch(Exception e) {
e.printStackTrace();
stmt = null;
}
}
};
The error means that you are using executeUpdate() when you should be using executeQuery()
executeUpdate() is for executing updates (duh)
executeQuery() is for searching the database and returning a ResultSet
Hope this helps
Related
I'm trying to create the tables directly form Java instead of creating them using phpMyAdmin. The code looks like that runs smooth, but when the queries arrive, it gives some kind of error that I'm trying to identify and I'm not capable. Here's the code I've been trying:
package filmoteca;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class GestionBDD {
private static String datosConexion = "jdbc:mysql://127.0.0.1:3306/";
private static String baseDatos = "cine";
private static String usuario = "root";
private static String pass = "";
private static String tabla = "pelicula";
private Connection con;
public GestionBDD() {
try {
con = DriverManager.getConnection(datosConexion, usuario, pass);
try{
crearBDD();
crearTablas();
}catch(Exception e){
e.printStackTrace();
}
}catch(SQLException e) {
e.printStackTrace();
}
}
public void crearBDD() throws Exception{
String query = "CREATE DATABASE IF NOT EXISTS"+ baseDatos +";";
Statement stat = null;
try{
stat = con.createStatement();
stat.executeUpdate(query);
con = DriverManager.getConnection(datosConexion+baseDatos, usuario, pass);
}catch(SQLException e){
e.printStackTrace();
}finally{
stat.close();
}
}
public void crearTablas() throws Exception{
String query = "USE DATABASE "+baseDatos+";"+
"CREATE TABLE IF NOT EXISTS"+" "+tabla+"("
+ "titulo VARCHAR(30), "
+ "director VARCHAR(30), "
+ "pais VARCHAR(30), "
+ "duracion FLOAT, "
+ "genero VARCHAR(30));";
Statement stat = null;
try{
stat = con.createStatement();
stat.executeUpdate(query);
con = DriverManager.getConnection(datosConexion+baseDatos, usuario, pass);
}catch(SQLException e){
e.printStackTrace();
}finally{
stat.close();
}
}
}
I am working in command prompt this is my code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnf) {
System.out.println("Driver could not be loaded: " + cnf);
}
}
public static void main(String[] args)
{
String connectionUrl = "jdbc:mysql://localhost:3306/mysql";
String dbUser = "root";
String dbPwd = "admin";
Connection conn;
ResultSet rs;
String queryString = "SELECT ID, NAME FROM exptable";
try {
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
Statement stmt = conn.createStatement();
// INSERT A RECORD
stmt.executeUpdate("INSERT INTO exptable (name) VALUES (\"TINU K\")");
// SELECT ALL RECORDS FROM EXPTABLE
rs = stmt.executeQuery(queryString);
System.out.println("ID \tNAME");
System.out.println("============");
while (rs.next()) {
System.out.print(rs.getInt("id") + ".\t" + rs.getString("name"));
System.out.println();
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException sqle) {
System.out.println("SQL Exception thrown: " + sqle);
}
}
}
i am getting error like
java.lang.ClassNotFoundException and java.sql.SQLException
so may i know what mistake have i made
You might have missed the classpath in your java command. While executing from command prompt you must mention the class path along with your command.
java -cp
ex:
java -cp /home/test/jars:/home/test/src com.test.Lab
While executing update by jdbc on Oracle dbms, my program hangs. I think it is waiting for another process/user to release lock on the rows or table that I am trying to update. So what are the possible causes for this problem and how can I solve it?
I am making calls to the dbms through jdbc as show here:
public static void updateEmployee(String name,int id) throws ClassNotFoundException
{
Connection con=null;
PreparedStatement st=null;
String driver= "oracle.jdbc.driver.OracleDriver";
String username="someuser";
String password="pwd";
String url="jdbc:oracle:thin:#hostname:1521:ORAJAVADB";
Class.forName(driver);
try
{
con=DriverManager.getConnection(url,username,password);
st=con.prepareStatement("update employee set employeeName=? where
employeeId = ? ");
st.setString(1,name);
st.setInt(2,id);
st.executeUpdate();
st.close();
con.close();
}
catch(SQLException ex)
{
}
}
I made this code for update function using java with oracle database. I hope it will help you. Good Luck
package updatemethod;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import oracle.jdbc.pool.OracleDataSource;
public class UpdateMethod {
public static String url = "jdbc:oracle:thin:#mohammed:1521:XE";
public static String user = "md";
public static String password = "md";
public static String query;
public static Connection conn;
public static Statement smt = null;
// CREATE DATABASE CONNECTION
public static void getDBConnection() throws SQLException{
OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(url);
conn = ds.getConnection(user, password);
System.out.println("DataBase Accessed!");
}
public static void updateEmployee(String nID, String newFirst, String newLast, String newJob)throws SQLException{
try{
smt = conn.createStatement();
smt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = smt.executeQuery("SELECT ID, FIRSTNAME, LASTNAME, JOB FROM MD.EMPLOYEE1");
while(uprs.next()){
int newID = Integer.parseInt(nID);
uprs.updateInt("ID", newID);
uprs.updateString("FIRSTNAME", newFirst);
uprs.updateString("LASTNAME", newLast);
uprs.updateString("JOB", newJob);
uprs.updateRow();
System.out.println("DataBase Updated\n");
System.out.println("ID " + newID + " " + "FIRSTNAME " + newFirst + " " + "LASTNAME " + newLast + " " + "JOB " + newJob);
}
}
catch(SQLException er){
System.out.println(er);
}
}
public static void main(String[] args) throws SQLException {
// CREATE CONNECTION BY CALLING getDBConnection();
getDBConnection();
// NOW, CALL OUR updateEmployee(String,String,String,String) FUNCTION
updateEmployee("123", "mohammed", "Jamal", "Computer Technique Engineer");
}
}
I have added JAR file "mysql-connector-java-5.1.36-bin" and have created database "UserScore" and under that table "ScoreSheet".I have added a row in ScoreSheet (Name,Score) value ('Kamal',40) to verify but the code throws a lot of exceptions on connection.I am using Eclipse + Xampp.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class SQLDriver{
public static void main(String[] args){
try{
//Accessing driver from jar file
Class.forName("com.mysql.jdbc.Driver");
//Get connection through creating a variable 'myConn'
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/UserScores");
//Create statement
PreparedStatement statement = myConn.prepareStatement("select * from 'scoresheet'");
//Execute SQL Query
ResultSet result = statement.executeQuery();
//Process the result set
while(result.next()){
System.out.println(result.getString(1)+" "+result.getString(2));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
I always do it like this:
// Hostname
private static final String dbHost = "127.0.0.1";
// Port -- Standard: 3306
private static final String dbPort = "3306";
// Database name
private static String database = "database"; //
// Database user
private static final String dbUser = "root";
// Datenbankpasswort
private static final String dbPassword = "";
private Statement s;
public void Connect() {
try {
Class.forName("java.sql.Driver"); // load driver
Connection conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":"
+ dbPort + "/" + database + "?" + "user=" + dbUser + "&"
+ "password=" + dbPassword); // try to connect with your attributes
s = conn.createStatement();
} catch (ClassNotFoundException e) { //
l.error("Driver not found " + e);
} catch (SQLException e) {
l.error("Connect not possible" + e);
}
}
Your query should specify Scoresheet without '
Specify the username and password when calling DriverManager.getConnection
The second row in your table does not appear to be of type string. Invoke result.getInt(2) rather than result.getString(2)
I am trying to execute simple query using below DbQuery.java class which uses DbConnector to get a Connection from DriverManager.
note:
I have already included "mysql-connector-java-5.1.25-bin.jar" on my
classpath via: export
CLASSPATH=$CLASSPATH:/home/me/ocpjp/chapter-10/mysql-connector-java-5.1.25/mysql-connector-java-5.1.25-bin.jar
I am able to connect to mysql with "mysql -uroot -ptcial
addressBook", if it matters.
have also tried running with '-cp'
argument with no avail.
I am able to get my #3 DbConnect.java class to say "Database connection established".
Also #4 DbQueryWorking.java has no issues and provides expected output .
Can you please help me understand what is the issue here ?
1) DbConnector.java
package com.me.ocpjp.chapter10;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnector{
public static Connection connectToDb() throws SQLException{
String url = "jdbc:mysql//localhost:3306/";
String db = "addressBook";
String username = "root";
String password = "tcial";
return DriverManager.getConnection(url+db, username, password);
}
}
2) DbQuery.java
package com.me.ocpjp.chapter10;
import java.sql.Connection ;
import java.sql.Statement ;
import java.sql.ResultSet ;
import java.sql.SQLException ;
import com.me.ocpjp.chapter10.DbConnector;
public class DbQuery{
public static void main(String[] args){
try(Connection connection = DbConnector.connectToDb();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while(resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo") );
}
}catch(SQLException sqle){
sqle.printStackTrace();
System.exit(-1);
}
}
}
3) DbConnect.java
package com.me.ocpjp.chapter10;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbConnect{
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/";
String database = "addressBook";
String userName = "root";
String password = "tcial";
try(Connection connection = DriverManager.getConnection(url+database, userName, password)){
System.out.println("Database connection established");
}catch(Exception e){
System.out.println("Database connectioni NOT established");
e.printStackTrace();
}
}
}
4) DbQueryWorking.java
package com.me.ocpjp.chapter10;
import java.sql.Connection ;
import java.sql.Statement ;
import java.sql.ResultSet ;
import java.sql.SQLException ;
import java.sql.DriverManager;
public class DbQuery{
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/";
String database = "addressBook";
String userName = "root";
String password = "tcial";
try(Connection connection = DriverManager.getConnection(url + database, userName, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while(resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo") );
}
}catch(SQLException sqle){
sqle.printStackTrace();
System.exit(-1);
}
}
}
it looks like that the URL in DbConnector.java is wrong. A colon is missing. The url must be:
jdbc:mysql://localhost:3306/
and not
jdbc:mysql//localhost:3306/
your URL is wrong, you're missing a colon in it, it should be:
String url = "jdbc:mysql://localhost:3306/";