Does anyone have any ideas of how to connect Access 2010 to java jdbc. I use this method, but when I call it, it doesn't work:
public void loadDb(){
try{
Class.forName("sun.jdbc.JdbcOdbcDriver");
File f = new File(System.getProperty("user.dir"))
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Acess Driver (*.mdb, *.accdb)}; DBQ="+ f.getPath() + "//db//JavaAccess.accd","","");
st = con. createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
}catch(ClassNotFoundException e){e.printStackTrace();
}catch(SQLException e){e.printStackTrace();}
}
//con and st are already defined
According to msdn it should be sun.jdbc.odbc.JdbcOdbcDriver. So replace this line of code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Spelling error? Perhaps this line:
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Acess Driver (*.mdb, *.accdb)}; DBQ="+ f.getPath() + "//db//JavaAccess.accd","","");
should be
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ="+ f.getPath() + "//db//JavaAccess.accd","","");
Access has 2 C's
Create connection
public static Connection getConnection() {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:anime"; //anime is the database
String username = "ipieluser"; //leave blank if none
String password = "ipielpassword"; //leave blank if none
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
How to call:
public static void main(String args[]) {
try {
Connection conn = getConnection();
Statement st = conn.createStatement();
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM localTable");
//get and displays the number of columns
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
st.close();
conn.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
Use UCanAccess JDBC Driver :
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); // can be omitted in most cases
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<mdb or accdb file path>",user, password);
e.g.:
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://c:/pippo.mdb");
So for your example it will be
con = DriverManager.getConnection("jdbc:ucanaccess://"+f.getPath()+"/db/JavaAccess.accd")
Rishab's reply helped me to connect to my access database.
I did following correction in the code:
Instead of
String url = "jdbc:odbc:anime"; //anime is the database
I did
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=" + "d://institute//institutedata.accdb";
I explicitly defined driver and full database name with path and extension.
As today only we face the same problem and found that to check the version of java if your
version of java if the version of the java is above 7 then the sun.jdbc.odbc.JdbcOdbcDriver will not be supported so just check the version of the java.
Related
I am trying to connect to a local MariaDB Database via eclipse and tomcat. When I run the Program i get this message:
java.sql.SQLNonTransientConnectionException: Could not connect to localhost:8080 : unexpected end of stream, read 0 bytes from 4 (socket was closed by server)
at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:240)
at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.getException(ExceptionMapper.java:171)
at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1132)
at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:561)
at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:175)
at org.mariadb.jdbc.Driver.connect(Driver.java:92)
This is the code i am executing:
public void verbinde() {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName("org.mariadb.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(
"jdbc:mariadb://localhost:8080/test?user=root&password=root");
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE REGISTRATION "
+ "(id INTEGER not NULL, "
+ " first VARCHAR(255), "
+ " last VARCHAR(255), "
+ " age INTEGER, "
+ " PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} 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
the default port of MariaDB is 3306 not 8080
jdbc:mariadb://localhost:3306/test?user=root&password=root
8080 is the port where your tomcat is running
BTW: use try-with-resources instead of the try-catch-finally block
I'm trying to connect to my remote database on my VPS using a desktop application built with JAVA.
I have granted access to my ip address by adding this line in the VPS:
After that I have created a JAVA class to test the conenction:
package smt.agm.launcher;
import java.sql.*;
public class Test {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://my_vps:port/my_database";
// Database credentials
static final String USER = "user";
static final String PASS = "password";
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 * FROM table";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String col1= rs.getString("column1");
String col2= rs.getString("column2");
//Display values
System.out.print("column1: " + col1 + ", column2: "+col2);
}
//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
}
But I have faced this exception:
PacketTooBigException: Packet for query is too large (5 526 600 > 65 535). You can change this value on the server by setting the 'max_allowed_packet' variable.
So I did some research and I have found a way to increase the variable max_allowed_packet using ssh:
vi /etc/my.cnf
and I have increased the value of max_allowed_packet to 500M.
Unfortunately this didn't help and I've got the same exception with the same values:
PacketTooBigException: Packet for query is too large (5 526 600 > 65 535). You can change this value on the server by setting the 'max_allowed_packet' variable.
What am I missing here ?
I need to convert result set into csv for any database (not just postgres)
Empty csv file is being created when I use opencsv.
Here's the code of doGet method in the servlet:
final String JDBC_DRIVER = "org.postgresql.Driver";
final String DB_URL = "jdbc:postgresql://localhost:5432/postgres";
// Database credentials
final String USER = "postgres";
final String PASS = "12345";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
PreparedStatement ps = null;
Connection conn = null;
try {
// Register JDBC driver
Class.forName("org.postgresql.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
//stmt = conn.createStatement();
String sql = "SELECT * FROM users";
ps = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
/*if(rs.next()){
System.out.println("Name = "+rs.getString("first_name"));
}*/ //prints name so rs is not empty
//rs.first();
CSVWriter writer = new CSVWriter(new FileWriter("Test.csv"));
//even tried with seperator '\t' or ','
writer.writeAll(rs, true);
writer.close();
out.println("</body></html>");
// Clean-up environment
rs.close();
ps.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 (ps != null)
ps.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
} //end try
Not sure what's the error. Tried different way but csv is always empty.
Even tried writer.flush(), rs.beforeFirst(), rs.first() nothing works.
Is your problem that you do not see data in the html - if that is the case then instead of creating a new FileWriter in the CSVWriter just pass in you out variable.
Or is it that you checked the Test.csv and file and nothing is there? if so then first check to see if there is actually data in the result set by adding the following after executeQuery:
rs.last();
long numberOfRecords = rs.getRow();
rs.beforeFirst();
System.out.println("Number of Users in table is: " + numberOfRecords);
When I try to run the simple Java program below from the CentOS 7 terminal, I get a java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error at the line of code that says Class.forName("com.mysql.jdbc.Driver");. How can I resolve this and similar errors in the code below so that the simple program below will run without errors?
Here is what I have so far:
I navigate to /path/to/ and then type:
javac somepackage/TestJDBC.java
java somepackage.TestJDBC
This results in the error described above. The full code of this simple program is:
package somepackage;
//STEP 1. Import required packages
import java.sql.*;
public class TestJDBC {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/somedb?autoReconnect=true";
// Database credentials
static final String USER = "usrname";
static final String PASS = "pword";
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 FROM peeps";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
//Display values
System.out.print("ID: " + id);
System.out.println(", name: " + name);
}
//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
You need the library - cannot simplify that away. Previously I'm guessing you used a web app server like JBoss that provided the library for you. Now you're outside the container.
First download the Connector/J jar (contains the JDBC driver class com.mysql.jdbc.Driver) from http://dev.mysql.com/downloads/connector/j/5.0.html.
Then with the jar file in the current working directory, invoke your program something like this:
java -cp mysql-connector-java-5.n.nn.bin.jar:. somepackage.TestJDBC
Also see this SO post: Including jars in classpath on commandline (javac or apt)
HTH
Locate (or upload) the mysql driver jar to the server, then run your code with
java -classpath /path/to/mysql-connector-java-5.0.8-bin.jar:. somepackage.TestJDBC
Adjust the version to whatever you're using.
I am using the JDBC driver to connect to a mysql database and using the "LOAD DATA INFILE" command in my java application to load(insert) a text file into the database. I am getting the following error: Data truncation: Data too long for column xxx at row 1.
However if I load the same text file manually by logging into the database and entering the SQL manually, the data loads fine.
Can someone pelase tell me what the error might be?
I am running this on Red Hat Enterprise Linux Server release 5.8 and the jdk version is 1.5.0_16 if that helps
This is the function used to load the data
public static void loaddata(Connection conn, String filename, String tablename)
{
try{
Statement stmt = null;
stmt = conn.createStatement();
File file = new File(filename);
file.getAbsolutePath().replace("\\", "\\\\");
String cmd = "LOAD DATA INFILE '"
+ file.getAbsolutePath().replace("\\", "\\\\")
+ "' INTO TABLE " + tablename + " FIELDS TERMINATED BY \'^\'";
stmt.executeUpdate(cmd);
System.out.println("cmd :" + cmd);
}
catch(SQLException sqle){
sqle.printStackTrace();
}
}
This is the function to create the JDBC connection:
public static Connection createConnection()
{
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(Exception e) {
e.printStackTrace();
}
try {
String url = ""; //URL mentioned in the actual code
conn = DriverManager.getConnection(url, user, pass);
} catch (SQLException sqe1) {
sqe1.printStackTrace();
}
return conn;
}