How to create a table in access database using java - java

i need to create a table in access database. For this i tried with the following code
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.execute("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
But it throws the following error " ERROR: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified ".

It is possible with UCanAccess
con = ConnectMdb(homedirectory+"/"+"Centre.accdb");
if (con != null) {
Statement st3 = null;
try {
st3 = (Statement) con.createStatement();
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
String sqlq3 = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
// System.out.println(sqlq1);
// ResultSet rs3 = null;
try {
st3.execute(sqlq3);
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
Try this.

Below Corrected Code may help you:
mistake in connection string and while creating table. need to use executeUpdate method
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.executeUpdate("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}

The problem is on this line:
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
which you should change to:
String connURL = "jdbc:odbc:DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
i.e. you need to remove the semi-colon between jdbc and odbc.

Related

Query Java doesn't execute

I'm trying to execute a query on eclipse at my Java program, but it always exit with a exception and don't execute the query, I read a lot of posts here but no one of them could help me with this.
public static ResultSet queryAccAmount;
public static String query = " SELECT COUNT(*) s FROM (SELECT L.ACCNUMBER AS AN, L.PROD AS PRD "
+ " FROM LTRANS(nolock) L, AN(nolock) ANM "
+ " WHERE DATA BETWEEN 20210101 AND 20210228 "
+ " AND L.PRD IN (1, 2, 3) "
+ " AND L.ACCNUMBER = ANM.ACCNUMBER "
+ " AND L.ISS = ANM.ISS "
+ " AND L.PROD = ANM.PROD "
+ " AND L.MESSAGECODE <> 'MESSAGE' "
+ " GROUP BY L.PROD, L.ACCNUMBER) S; ";
public static void main(String[] args) throws InterruptedException {
Connection c = connect();
int accAmount = 0;
try {
queryAccAmount = c.createStatement().executeQuery(query);
accAmount = Integer.parseInt(queryAccAmount.getString(1));
LOG.info("Mounth total: " + accAmount);
} catch (Exception ex) {
System.out.println(ex);
} finally {
TimeUnit.SECONDS.sleep(10);
disconnect();
}
}
The error when execute the program:
JavaError
But at the base have data:
DataBase
I don't know what is wrong with this, who could help me I'm already appreciate!
You need to call executeQuery once and then read the results in loop for example Updating my comment with working example:-
import java.sql.*;
public class JDBCConnector {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "root";
static final String PASS = "mysql";
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
Try to do this in your try:
try {queryAccAmount = c.createStatement().executeQuery(query);
if(queryAccAmount.next){
accAmount = Integer.parseInt(queryAccAmount.getString(1));}
LOG.info("Mounth total: " + accAmount);
} catch (Exception ex) {
System.out.println(ex);
} finally {
TimeUnit.SECONDS.sleep(10);
disconnect();
}

How to tell the mysql table to retrieve the next matching record into my default table model

How do I tell my java program to retrieve the next matching record into my default table model.
Below is my home work so far.using jTable tb1 and default table model dtm is compulsory for me.
private void Show_My_LettersActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(url, "root", "root");
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * from LCI where SUB_ID = '" + SUB_ID_.getText() + "' AND L_DATE = '" + DATE.getText() + "'";
ResultSet rs1, rs2, rs3, rs4, rs5, rs6, rs7;
rs1=j.getData("select COUNT(*) from LCI");
try (ResultSet rs = stmt.executeQuery(sql)) {
DefaultTableModel dtm = (DefaultTableModel) tb1.getModel();
while (rs.next()) {
String L_ID_ = rs.getString("L_ID");
String L_DATE_ = rs.getString("L_DATE");
String heading = rs.getString("HEADING");
String sub_id = rs.getString("SUB_ID");
System.out.print("ID: " + L_ID_);
System.out.print(", Letter date: " + L_DATE_);
System.out.print(", Heading " + heading);
System.out.println(", Subject ID " + sub_id);
/* This gives the correct out put when debug is done.
But the below code doesn't retrive the full out put.
It gives only the very first record matching with the user inputs*/
Vector v = new Vector();
Vector v1 = new Vector();
Vector v2 = new Vector();
Vector v3 = new Vector();
JOptionPane.showMessageDialog(this, "Done");
dtm.getColumnName(1);
v.addElement(rs.getString(1));
dtm.addColumn(v);
dtm.getColumnName(3);
v1.addElement(rs.getString(3));
dtm.addColumn(v1);
dtm.getColumnName(10);
v2.addElement(rs.getString(10));
dtm.addColumn(v2);
// stmt.executeQuery("SELECT * FROM LCI WHERE L_ID IN(SELECT (L_ID + 1)FROM LCI WHERE L_DATE = '"+DATE.getText()+"'");
dtm.addRow(v3);
//stmt.executeQuery("SELECT * FROM LCI WHERE L_ID IN(SELECT (L_ID '"+(+1)+"')FROM LCI WHERE L_DATE = '"+DATE.getText()+"'");
}
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}// TODO add your handling code here:
}

Java sqlite row disappear after Select query

I have a sqlite db file created by other program, and checked everything is fine.
Then after doing select query to get some data, some of the row disappear after this process. I tried to use prepareStatement and though it worked but this remained.
my code
private ForecastTableItem selectItemPrepareStatement(String tableName, String columnName, String name) {
ForecastTableItem item = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + dbLocation);
System.out.println("Selecting item from tableName: "+tableName + " of col: "+columnName + " : "+name);
String query = "SELECT * FROM " + tableName + " WHERE " + columnName + "=? COLLATE NOCASE";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, name);
rs = pstmt.executeQuery();
if (rs.next()) {
if (tableName.equalsIgnoreCase("mainTable")) {
item = new ForecastTableItem();
item.setId(rs.getInt("Id"));
item.setTitle(rs.getString("title"));
item.setLink(rs.getString("link").toLowerCase());
item.setPositionType(rs.getString("positionType"));
item.setPackageName(rs.getString("packageName"));
item.setCsvFilePath(rs.getString("csvFilePath"));
item.setSubpackageName(rs.getString("subpackageName"));
item.setTimeFrame(rs.getString("timeFrame"));
item.setForecastDate(rs.getString("forecastDate"));
item.setTargetDate(rs.getString("targetDate"));
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
if(pstmt != null) try{ pstmt.close();} catch(SQLException e){};
if(rs != null) try{ rs.close();} catch(SQLException e){};
if(conn != null) try{ conn.close();} catch(SQLException e){};
}
return item;
}
after COLLATE NOCASE use semi-column
"SELECT * FROM " + tableName + " WHERE " + columnName + "= ? COLLATE NOCASE;";

ResultSet returns only the last record from the table

The below java method sets the ResultSet data to a bean class and I am fetching the data. But, the method runHiveQuery() returns only one row that is the last record in the table. While debugging the code i found that the resultset is being looped twice as we have two records. But, while returning the bean class object there is some issue as it retrieves only one record.
Unable to find what is going wrong.
public CSPData getCSPData() throws SQLException {
try {
String drivername = "org.apache.hive.jdbc.HiveDriver";
Class.forName(drivername);
connection = DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:20000/");
statement = connection.createStatement();
resultset = statement.executeQuery(
"select distinct db_name as db_name,db_server_name as db_server_name,lower(db_name) as l_db_name,lower(db_server_name) as l_server_name,regexp_replace(lower(db_server_name), '-', '_') as server_name,db_server_name_secondary as db_server_name_secondary from csp.curated_input");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
while (resultset.next()) {
cspdata.setDbName(resultset.getString("db_name"));
cspdata.setDbServerName(resultset.getString("db_server_name"));
cspdata.setDbServerNameSecondary(resultset.getString("db_server_name_secondary"));
cspdata.setlDbName(resultset.getString("l_db_name"));
cspdata.setlServerName(resultset.getString("l_server_name"));
cspdata.setServerName(resultset.getString("server_name"));
}
return cspdata;
}
public void runHiveQuery() throws SQLException {
CSPData cspdata = hivedao.getCSPData();
String hive_db = "csp";
String dbname = cspdata.getDbName();
String dbservername = cspdata.getDbServerName();
String servername = cspdata.getlServerName();
String drop = "Drop table if exists " + hive_db + "." + "IB_C3_" + dbname + "_" + dbservername;
String insert = "insert into table " + hive_db + "." + "IB_export_log select " + "\'ib_c3_" + dbname + "_"
+ servername + "\' from " + hive_db + "." + "dual limit 1";
System.out.println(drop);
System.out.println(insert);
}
Your code returns the last record since it only returns a single record. You should return a List :
public List<CSPData> getCSPData() throws SQLException {
List<CSPData> result = new ArrayList<>();
try {
String drivername = "org.apache.hive.jdbc.HiveDriver";
Class.forName(drivername);
connection = DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:20000/");
statement = connection.createStatement();
resultset = statement.executeQuery(
"select distinct db_name as db_name,db_server_name as db_server_name,lower(db_name) as l_db_name,lower(db_server_name) as l_server_name,regexp_replace(lower(db_server_name), '-', '_') as server_name,db_server_name_secondary as db_server_name_secondary from csp.curated_input");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
while (resultset.next()) {
CSPData cspdata = new CSPData ();
cspdata.setDbName(resultset.getString("db_name"));
cspdata.setDbServerName(resultset.getString("db_server_name"));
cspdata.setDbServerNameSecondary(resultset.getString("db_server_name_secondary"));
cspdata.setlDbName(resultset.getString("l_db_name"));
cspdata.setlServerName(resultset.getString("l_server_name"));
cspdata.setServerName(resultset.getString("server_name"));
result.add(cspdata);
}
return result;
}

no results were returned by the query

Connection con = null;
Statement stmt = null;
Statement resultStmt = null;
ResultSet rs = null;
try {
// load database driver driver
System.out.println("Database driver is: " + DataSource.getClassName());
Class.forName(DataSource.getClassName());
// connect to database from a given URL with a given username and password
System.out.println("Database URL is: " + DataSource.getURL());
con = DriverManager.getConnection(DataSource.getURL(), DataSource.getUserName(), DataSource.getPassword());
// create an SQL statement object
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO leadcustomer " + "VALUES(1, 'junwei', 'Li', 'heaven road','test#test.com')");
String SQLStatement = "SELECT * FROM leadcustomer";
System.out.println("Q1 SQL Statement is: " + SQLStatement);
rs = resultStmt.executeQuery(SQLStatement);
while (rs.next()) {
int customerid = rs.getInt("customerid");
String fistname = rs.getString("firstname");
String surname = rs.getString("surname");
String billAddress = rs.getString("billingAddress");
String email = rs.getString("email");
System.out.println("customerid : " + customerid);
System.out.println("firstname : " + fistname);
System.out.println("surname : " + surname);
System.out.println("billingAddress : " + billAddress);
System.out.println("email : " + email);
System.out.println(customerid + " : " + fistname + "--" + surname + "--" + billAddress + ":" + email);
}
con.close();
// extract name from first row and print
} catch (SQLException e) {
// print details of SQL error
// could be multiple errors chained together
System.err.println("Error(s) occurred");
while (e != null) {
System.err.println("SQLException : " + e.getMessage());
System.err.println("SQLState : " + e.getSQLState());
System.err.println("SQLCode : " + e.getErrorCode());
e = e.getNextException();
System.err.println();
}
}
I'm trying to insert data and select the table after inserted. But it returns the error message "no results were returned by the query"
I did use executeUpdate and executeQuery for different SQL statement.
Any suggestion for that?
BTW, the insert action is running successful.
The only thing I want is just to solve out the error and execute the select statement print out the table..
Your resultStmt hasn't been initialized. Add
resultStmt = con.createStatement();
before
rs = resultStmt.executeQuery(SQLStatement);

Categories