My code for connection with access database is this...its working fine here... i have tried to connect my database with java derby embedded database but always getting sql exception assuming the same table what changes do i need to connect my application with java derby embedded database??
package database;
import java.sql.*;
import javax.swing.JOptionPane;
public class database {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
String url = "jdbc:odbc:personnew";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection(url);
Statement st=con.createStatement();
String sql="SELECT * FROM Person";
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
String id=rs.getString("id");
String name=rs.getString("name");
String fathername=rs.getString("fathername");
JOptionPane.showMessageDialog(null,id+"\t"+name+"\t"+fathername);
}
// TODO code application logic here
}catch(Exception sqlEx){
System.out.println("Sql exception");
}
}
}
For one thing, You would need to use the correct JDBC driver; org.apache.derby.jdbc.EmbeddedDriver
http://db.apache.org/derby/papers/DerbyTut/embedded_intro.html
The tutorial in general is probably where you want to start as it tells you everything you need to know:
http://db.apache.org/derby/papers/DerbyTut/index.html
Related
I have a new H2 test DB all setup and have no issue getting to it locally.
I used this site to help https://www.tutorialspoint.com/h2_database/h2_database_jdbc_connection.htm
I took the code and put it up on an Amazon web server and can confirm it is indeed running and can, again, locally add data to it and access it VIA code and the H2 console. The H2 console can even be reached from my remote PC.
Now on my PC I am trying to get to the server VIA JDBC but cannot. Server is even set up for the TCP server.
in the properties file
spring.datasource.url=jdbc.h2.mem.test
In the application.java file, in a try-catch, and it reports the server did start.
Server.createTcp.Server().start();
The DB has a table called testable in there with server columns and test rows. And Again locally and even in the H2 console, I can get to the data no problem.
I tried several ways to list the URL in Java code to get to the server VIA JDBC.
here is the fake URL that I can get to a website hosted there just fine as well as the H2 console.
https://www.mywebsitehostedonamazon.com/h2
I have added this to my code to the connection for the URL.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class H2jdbcCreateDemo {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:tcp://https://www.mywebsitehostedonamazon.com:8082/test";
// Database credentials
static final String USER = "sa";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 1: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 2: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 3: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "SELECT * FROM testable LIMIT 1";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
// STEP 4: Clean-up environment
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!");
}
}
When I run this I receive a Zero length string error for line conn = DriverManager.getConnection(DB_URL,USER,PASS);
If I change up the URL then I get a connection time out. jdbc:h2:tcp://www.mywebsitehostedonamazon.com:8082/test
If I change up the URL then I get a connection time out. jdbc:h2:tcp://www.mywebsitehostedonamazon.com:8082/mem:test
If I change up the URL then I get an error that the Table "testable" not found. jdbc:h2:mem://www.mywebsitehostedonamazon.com:8082/mem:test
Can anyone help out with this?
I have a basic Java application (with a GUI) that uses a linked list to add/remove/modify Customer objects and I want to store them in a database (Oracle DB express to be exact)?
As I understand it, I have to create a table with some tool, and the use that tool to auto-generate a Java class that would allow me to communicate with the DB. How far off am I with this?
Just to make your question clear, What tool have you used to generate your java code?
I recommend you to avoid using code generation tool in case you want to learn in and out of Java.Here is an example of how you can connect your SWING application with Oracle DB,MySQL,Derby and many more other databases.
Connection con;
Statement smt;
ResultSet rs;
String user="databaseuser";
String pass="password";
String path="jdbc:oracle:thin:#localhost:1521:Sampledb"; //put db url here
try{
con=DriverManager.getConnection(path, user, pass);
smt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String SQL="SELECT *FROM Registered_users_tb "; //Your Query here
rs=smt.executeQuery(SQL);
rs.moveToInsertRow();
//First param is db column name,second param is variable name
rs.updateString("USERNAME", username);
rs.updateString("FNAME", fname);
rs.updateString("MNAME", mname);
rs.updateString("LNAME", lname);
rs.updateString("GENDER", gender);
rs.updateString("DEPARTMENT", dept);
rs.insertRow();
rs.close();
smt.close();
}
catch(SQLException err){
JOptionPane.showMessageDialog(Classname.this,err.getMessage());
}
For creating a complete new database, oracle provide a gui tool called DBCA. I found a couple of links to use this tool: Link 1 and Link 2
This tutorial teaches how to access an Oracle database. For accessing such an database you need additional drivers found here. Here an short example how to access such a database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
class DatabaseAccess
{
public static void main(String [] args)
{
Connection connection = null;
try
{
Class.forName("oracle.jdbc.OracleDriver");
String dbPath = "jdbc:oracle:thin:#localhost:1521:myDatabase";
String username = "user";
String password = "password";
connection = DriverManager.getConnection(dbPath, username, password);
if(connection != null)
{
System.out.println("Connected with database");
Statement statement = connection.createStatement();
ResultSet results = statementt.executeQuery("SELECT * FROM myTable");
while(result.next())
{
System.out.println(result.getString("myString"));
}
}
catch(ClassNotFoundException | SQLException exc)
{
exc.printStackTrace();
}
finally
{
try
{
connection.close();
}
catch(SqlException exc)
{
exc.printStackTrace();
}
}
}
}
For an more advanced example visit the given link.
I am a little bit confused,
I am trying to insert multiple rows to MS Access database from a java program using ucanaccess Java library.
I don't understand why the above (check title) SQL Exception is thrown when calling the 2nd insertRow() method?
The Exception is NOT thrown either by calling con.setAutoCommit(false); & con.commit(); methods or by re-executing the SQL query using the command rs = st.executeQuery(sql);. I also do not understand why the problem is solved by doing one of the above. What changes?
Thanks in advance.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class db1 {
private Connection con;
protected Statement st;
protected ResultSet rs;
public db1() {
connect();
}
public void connect() {
try {
String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
Class.forName(driver);
String db = "jdbc:odbc:Database1";
con = DriverManager.getConnection
("jdbc:ucanaccess://C:\\Users\\Κώστας\\Desktop\\Database1.accdb");
st = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE,
ResultSet.HOLD_CURSORS_OVER_COMMIT)
// con.setAutoCommit(false);
String sql = "select * from TableA";
rs = st.executeQuery(sql);
rs.insertRow();
// rs = st.executeQuery(sql);
rs.insertRow(); // HERE the SQL Exception is thrown.
// con.commit();
}
catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
new db1();
}
}
UCanAccess has some known issues with updatable ResultSets because it uses triggers on the HSQLDB backing tables to push the changes to the Access database file. A side effect of those triggers is that they can leave the HSQLDB ResultSet in an invalid state.
The problem you are experiencing may not manifest itself with con.setAutoCommit(false); because the triggers probably don't flush the changes to the Access database until the JDBC transaction is committed.
I want to be able to use my web service to be able to populate a database in MySQL. From the code below, I have connected to the database that I want to populate. How can I use the data that users import on my Web Service to populate MySQL database exchangeInformation. The Web service is working and everything works. I am just looking to be able to use the input of that data from the web service to populate my database in MySQL.
Any help would be greatly appreciated.
Thanks
Code Below:
package org.example.www.newwsdlfile3;
import java.sql.Connection;
import java.sql.DriverManager;
public class JavaMYSQL {
public static void main(String[] args) throws Exception {
getConnection();
}
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/exchangeinformation";
String username = "root";
String password = "admin";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
Use this page to see an example of creating a statement from a connection object and executing a query with it. As to your webservice information, I do not see where you are passing it in. That said you can use some simple string replacement to handle that:
String sql = "INSERT INTO tableName values(':value1', ':value2',':value3', etc)";
sql = sql.replace(":value1", dataFromService);
Something along those lines should get you started.
EDIT FOR CLARITY:
String sql = "INSERT INTO tableName values(':value1', ':value2',':value3', etc)";
String dataFromService = "EDIT";
sql = sql.replace(":value1", dataFromService);
System.out.println(sql);
Would net you an output:
INSERT INTO tableName values('EDIT',':value2','value3', etc)
I just got some errors in my Java oracle connectivity. Could anyone please help me with this? I have enclosed the code below. I'm getting this error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver..
this is the code
package md5IntegrityCheck;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class MD5IntegrityCheck
{
public static void main(String[] args)
{
String fileName,Md5checksum ,sql;
Connection con;
PreparedStatement pst;
Statement stmt;
ResultSet rs;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 =DriverManager.getConnection("jdbc:odbc:RecordTbl","scott","tiger");
}
catch(Exception ee)
{ee.printStackTrace( );}
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/****insert method******/
private static void setDefaultCloseOperation(String exitOnClose) {
// TODO Auto-generated method stub
}
static void setVisible(boolean b) {
// TODO Auto-generated method stub
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:RecordTbl","scott","tiger");
PreparedStatement pst = con.prepareStatement("insert into RecordTbl values(?,?)");
String fileName = null;
pst.setString(1,fileName);
String Md5checksum = null;
pst.setString(2,Md5checksum);
int i=pst.executeUpdate( );
System.out.println("recorded in database");
con.close( );
}
catch(Exception ee)
{ee.printStackTrace( );}
}
}
if (args.length <= 0)
{
Md5Gui gui = new Md5Gui();
gui.runGui();
}
else
{
DoWork runningProgram = new DoWork();
runningProgram.run(args);
}
}
}
Your question is vague:
In your exception, you're getting a ClassNotFoundException for a driver that pertains to MySQL. On your code, you're using a JDBC-ODBC Driver.
My suggestion is how did you configure your database connectivity. Let's start from there. Also, it would be better to add the exception stack trace to see exactly what's happening.
Edit: Visit this example if you want to know how to configure JDBC connection to Oracle Database. I fully recommend using the Oracle JDBC driver directly instead of connecting it to an ODBC Bridge.
I assume you might be running your program in IDE, so please add drivers jars in the classpath of project
You should look into any 3rd party library you're using whether there a MySQL database driver is needed. Although you write you are using an Oracle driver (though the JdbcOdbcDriver is provided by Java itself and has nothing to do with Oracle DB's) the exception is clearly stating that the MySQL is requested. Since you don't use it in the code you provided, there must be another database connection using MySQL.