This question already has an answer here:
invalid datetime format: insert date/time into Access from Java
(1 answer)
Closed 6 years ago.
conn = Connect.ConnectDB();
String sql = "insert into Ianouarios ("
+"id,"
+"Hmerominia,"
+"Agores,"
+"Pliromes,"
+"Eksoda,"
+ "Zhta,"
+"Metaforika,"
+"Pliromimetafo,"
+"Epitages,"
+"Xondriki,"
+"Noiki,"
+"Plirominoiki)"
+ "values("+a1.getText()+ ",'"+a2.getText()+"','"+a3.getText()+"','"+a4.getText()+"','"+a5.getText()+"','"+a6.getText()+"','"+a7.getText()+"','"+a8.getText()+"','"+a9.getText()+"','"+ a10.getText()+ "','"+a11.getText()+"','"+a12.getText()+"')" ;
try{
pst = conn.prepareStatement(sql);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Saved");
//UpdateJTable();
//conn.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
I have an ms access database and i am updating it with the jdbc-odbc driver.
Can anyone show me how to do the same to work with ucanaccess driver?
I tried their ucanaccess page examples but no luck.
Update: I did this:
conn = Connect.ConnectDB();
try{
String sql = "INSERT INTO Synola(id,Hmerominia,Agores,Pliromes,Eksoda,Zhta,Metaforika,Pliromimetafo,Epitages,Xondriki,Noiki,Plirominoiki) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)" ;
/* SimpleDateFormat ddmmyyyyFormat = new SimpleDateFormat("dd/MM/yyyy");
Timestamp ddmmyyyy = new Timestamp(ddmmyyyyFormat.parse(a2.getText()).getTime()); */
// String s=ddmmyyyy.toString();
pst = conn.prepareStatement(sql);
pst.setString(1, a1.getText());
pst.setString(2,a2.getText());
pst.setString(3, a3.getText());
pst.setString(4, a4.getText());
pst.setString(5, a5.getText());
pst.setString(6, a6.getText());
pst.setString(7, a7.getText());
pst.setString(8, a8.getText());
pst.setString(9, a9.getText());
pst.setString(10, a10.getText());
pst.setString(11, a11.getText());
pst.setString(12, a12.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Saved");
//UpdateJTableSynola();
// conn.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
And now the problem is the date from the a2.getText() field which i put into database as (dd/MM/yyyy).The error is unparseable date.How can i fix this?
As JDBC-ODBC Bridge has been removed in JDK8, what you can do is to use JDBC along with UCanAccess API to connect to an MSAccess database.
connection = DriverManager
.getConnection("jdbc:ucanaccess:////REMOTE-IP-ADDRESS/shared-folder/TestDB.mdb");
System.out.println("CONNECTION ESTABLISHED....");
Here is a small example(tested in Java 8) which connects to a remote MS-Access DB using JDBC/UCanAccess API. Make sure you have the following jars in your project build path.
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.0.jar
ucanaccess-2.0.9.5.jar
Code:
/**
* Connects to a remote MS-Access DB using JDBC/UCanAccess API.
*/
package miscellaneous;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ConnectRemoteDB {
public static void main(String[] args) {
initializeConnection();
}
/**
* Initializes remote database connection and inserts a record and closes the connection.
*/
private static void initializeConnection() {
System.out.println("Attempting Database Connection...");
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DriverManager
.getConnection("jdbc:ucanaccess:////REMOTE-IP-ADDRESS/shared-folder/TestDB.mdb");
System.out.println("CONNECTION ESTABLISHED....");
String insertTableSQL = "INSERT INTO Table1" + "(Name) VALUES"
+ "(?)";
preparedStatement = connection.prepareStatement(insertTableSQL);
preparedStatement.setString(1, "Sandeep");
preparedStatement.executeUpdate();
System.out.println("RECORD INSERTED...");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
System.out.println("CONNECTION CLOSED...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Related
I create a Java GUI and also created a database in MySQL workbench. But when I run my GUI and fill in the boxes I get the error:
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
at ......
Here is some of my Java code:
import java.sql.*;
public class expense {
/**
* Create the application.
*/
public expense() {
initialize();
Connect();
}
Connection con;
PreparedStatement pst;
ResultSet rs;
public void Connect()
{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/expense_db", "root","password");
}
catch (ClassNotFoundException ex)
{
ex.printStackTrace();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
.
.
.
.
.
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/expense_db", "root", "root");
pst = con.prepareStatement("insert into expenseTracker(date, item description, receipt number, amount, HST, total)values(?,?,?,?,?,?)");
pst.setString(1, date);
pst.setString(2, item_description);
pst.setString(3, receipt_num);
pst.setString(4, amount);
pst.setString(5, hst);
pst.setString(6, total);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record Addedddd!!!!!");
}
This is what my GUI looks like
Thanks in advance
I've already tried looking over multiple stackoverflow posts but I just can't seem to fix the error
i'm trying a online database connection for my java application, but it seems my database isn't connected well this is my java code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("sql101.epizy.com/epiz_26206530_sekolah","LOGIN","PASSWORD");
String query = "select * from users where username=? and password=?";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, jTextField1.getText());
pst.setString(2, jPasswordField1.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()) {
JOptionPane.showMessageDialog(null, "Login Berhasil");
jLabel7.setText(rs.getString(1));
welcome well = new welcome();
this.setVisible(false);
well.setVisible(true);
}
} catch (Exception e) {
}
}
i already input MySQL JDBC Driver library, by the way i'm using online database from https://infinityfree.net/
private void rtrBtnActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) depTbl.getModel();
try{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test1","admin","root");
Statement stmt = con.createStatement();
String query = "SELECT * FROM dept;";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String dno = rs.getString("deptno");
String dName = rs.getString("dname");
String lc = rs.getString("loc");
model.addRow(new Object[] {dno,dName,lc});
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Error In Connectivity");
}
}
Im trying to connect my JForm to the mysql database but not able to connect to the database, continuously executing catch statement "Error in Connectivity", please help how should i resolve this issue..............................................................................
Change the following line
Class.forName("java.sql.Driver");
to
Class.forName("com.mysql.jdbc.Driver");
in your code
This line of code is not correct - Class.forName("java.sql.Driver");
The java.sql.Driver is an interface. You need to provide the correct jdbc driver class for you appropriate db.
Such as for Oracle - Class.forName("oracle.jdbc.driver.OracleDriver");
I'm trying to teach myself how to connect to a msaccess database in java.
I have set up a class to access the database as follows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
Then I have my code which is just trying to select everything from the table.
I have created the table in msAccess and the code seems to get through the connect method in the above code without any problems, indicating it is finding the database and accessing it somewhat. The problem happens when I call the prepareStatement using the connection, i.e. code line:
stm = conn.prepareStatement(sql);
The full code is:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: \t \t" + id);
System.out.println("Name: \t \t" + name);
System.out.println("Gender: \t" + gender);
System.out.println("Address: \t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
You are receiving the error because when you try to call .prepareStatement the connection is closed. Your AccessDBConnect2 class contains a finally block that closes the connection before it returns. Fix that class so it leaves the connection open.
By the way, the JDBC-ODBC Bridge has been removed from Java 8 and is effectively obsolete. You might be interested in this alternative:
Manipulating an Access database from Java without ODBC
I've removed the obviously incorrect answer :) another possibility:
I would think the issue is in your connection to the database, try changing 'C:/Users/Bridget/Documents/EmployeeSys.accdb' to 'C:\\Users\Bridget\Documents\EmployeeSys.accdb'
I am trying to connect to jdbc database from servlet.I have separate class dbconnect for connection and inserting data to database.
Here is my dbconnect class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class dbconnect {
Connection conn;
Statement stm;
dbconnect(){
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
conn = DriverManager.getConnection
("jdbc:derby://localhost:1527/type","nika",
"mypass");
stm = conn.createStatement();
System.out.println("success");
String sql = "INSERT INTO USERS " + "VALUES (\"tsogiaidze#yahoo.com\", \"nika\", \"nika\", \"kaci\")";
stm.executeUpdate(sql);
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
In servlet I create new dbconnect object which must insert data to database,but it does not happen.
Can anyone tell me why it does not work?
I guess I make fundamental mistake.
Thank you.
For more details I have jsp file which sends html form data to this servlet and then I try to write these data to database using dbconnect class.
I have changed dbconnect class like this,now I use preparedstatement to write files but still does not work.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class dbconnect {
Connection conn;
Statement stm;
dbconnect(){
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/type","nika","nika");
stm = conn.createStatement();
System.out.println("success");
String sql = "INSERT INTO NIKA.USERS (mail, pass, gender, saxeli) VALUES (?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "tsogiaidze");
statement.setString(2, "nika");
statement.setString(2, "nika");
statement.setString(2, "kaci");
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
Use single quote to surround your texts.
String sql = "INSERT INTO USERS VALUES ("
+ "'tsogiaidze#yahoo.com', 'nika', 'nika', 'kaci')";
Or better, use a PreparedStatement:
String sql = "INSERT INTO USERS VALUES (?, ?, ?, ?)");
PreparedStatement stm = conn.prepareStatement(sql);
System.out.println("success");
stm.setString(1, "tsogiaidze#yahoo.com");
stm.setString(2, "nika");
stm.setString(3, "nika");
stm.setString(4, "kaci");
stm.executeUpdate();
Your insert statement is possibly wrong try this
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("making connection");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "welcome");
PreparedStatement stmt=conn.prepareStatement("INSERT INTO student(student_name,student_id,class) VALUES(?,?,?)");
stmt.setString(1, "abc");
stmt.setString(2, "4");
stmt.setString(3, "ukg");
stmt.executeUpdate();
System.out.println("query executed");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
Please change the driverclass and connectionString
in my case I used PostgreSQL with maven
add in pom.xml the following code
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.3.2</version>
</dependency>
in servlet class
Class.forName("org.postgresql.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/" + DB_NAME, USER, PASS);