i am trying to run app that runs on both hsql and mysql database, to when i run it i get this error :
java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "this.cnn" is null
at DataBase.DBcontrol.creer_piece(DBcontrol.java:122)
at pdr.FrontController.initialize(FrontController.java:160)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2573)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3237)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3194)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3163)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3136)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3113)
at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3106)
at pdr.Main.start(Main.java:13)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:832)
the chunck of code its reffering to in the first few lines are these :
public void creer_piece() throws ClassNotFoundException {
HConnexion dbc = new HConnexion(); cnn=dbc.connectDb();
PreparedStatement pss;
ResultSet s;
try {
req = "CREATE TABLE IF NOT EXISTS moussa.piece "
+ " (id VARCHAR(30), "
+ " atelier VARCHAR(30), "
+ " piece VARCHAR(30), "
+ " type VARCHAR(30) NULL, "
+ " pa VARCHAR(2) NULL, "
+ " ref1 VARCHAR(10) NULL , "
+ " ref2 VARCHAR(10) NULL , "
+ " quant INTEGER,"
+ " emp VARCHAR(30),"
+ " pos VARCHAR(30),"
+ " UNIQUE (id))";
pss = cnn.prepareStatement(req);
int e = pss.executeUpdate();
if (e > 0) {
JOptionPane.showMessageDialog(null, " erraurgg");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
and this one :
public void initialize(URL url, ResourceBundle rb) {
try {
run_wamp();
timer.schedule(new TimerTask() {
#Override
public void run() {
}
},10000);
dbc.creer_piece();dbc.creer_refs();dbc.creer_carte();dbc.creer_module();dbc.creer_eqip();
dbc.creer_c8();dbc.creer_secteur();dbc.creer_unite();dbc.creer_eqip();
dbc.creer_atelier();
dbc.get_natelier("SELECT * FROM moussa.atelier",combo_piece1);
} catch (Exception ex) {
Logger.getLogger(FrontController.class.getName()).log(Level.SEVERE, null, ex);
}
i think it has to do with my database, either the app is not creating the tables or i should create the tables manually and connect them, though i am just spit balling here, need some help please.
edit: so after looking at the comments, you guys told me that cnn is returning null because of the connectDB well here it is:
public class HConnexion {
private static String msg ;
Connection conn = null;Statement stm =null;
//=====================================================================================
public Connection connectDb() throws ClassNotFoundException {
String s = System.getProperty("user.home");
String JDBC_URL = "jdbc:hsqldb:Pdr_db;";
run_wamp();
String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database
conn = DriverManager.getConnection(path, "root", ""); //mysql database
stm=conn.createStatement();
stm.executeUpdate("create database IF NOT EXISTS moussa ");
return conn;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
this method (correct me if i am wrong) is supposed to connect me to my database (or create a new one in case there isn't any), so if cnn is returning null, does that mean that its not creating a database which the other methods can connect through cnn.
The null pointer exception is caused by your incorrect connection code which returns null.
// code for HSQLDB
public class HConnexion {
private static String msg = "Cannot connect";
Connection conn = null;Statement stm =null;
public Connection connectDb() throws ClassNotFoundException, SQLException {
String s = System.getProperty("user.home");
String JDBC_URL = "jdbc:hsqldb:Pdr_db;"; // this is a HSQLDB URL
run_wamp();
// String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull"; // we leave this out as you can connect only to one database, not two
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
// Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database - used
// conn = DriverManager.getConnection(path, "root", ""); //mysql database - unused
stm=conn.createStatement();
// stm.executeUpdate("create database IF NOT EXISTS moussa "); // only for mysql
return conn;
} catch (SQLException e) {
JOptionPane.showMessageDialog(msg, e);
throw e;
}
}
If you want to connect to MySQL, use this code
// code for MySQL
public class HConnexion {
private static String msg = "Cannot connect";
Connection conn = null;Statement stm =null;
public Connection connectDb() throws ClassNotFoundException, SQLException {
String s = System.getProperty("user.home");
// String JDBC_URL = "jdbc:hsqldb:Pdr_db;"; // this is a HSQLDB URL
run_wamp();
String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull"; // we use this for MySQL
try {
// Class.forName("org.hsqldb.jdbc.JDBCDriver");
Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database - unused
conn = DriverManager.getConnection(path, "root", ""); //mysql database - used
stm=conn.createStatement();
stm.executeUpdate("create database IF NOT EXISTS moussa "); // only for mysql
return conn;
} catch (SQLException e) {
JOptionPane.showMessageDialog(msg, e);
throw e;
}
}
Related
I am developing a simple app as a school project that is designed to be used by the client on his computer. I decide to use derby DB as it can work in embedded mode. However as everything works fine in eclipse, when I try to export it to executable jar file the app does not work properly.
I am trying to connect to DB and create tables if they don't exist as shown in the code. After the first launch of a jar new file named sampleDB appears on a screen so I guess that db is created. However, besides GUI components, the program does not work at all. I am executing those table methods in main as the first ones so I guess there may be something wrong with them, however, eclipse doesn't show any errors.
Here is a fragment of code responsible for connection and the creation of a table, that I mentioned.
public static Connection getConnection() throws Exception{
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Getting the Connection object
String URL = "jdbc:derby:sampleDB;create=true";
conn = DriverManager.getConnection(URL);
return conn;
}catch(Exception e) {System.out.println(e);}
return null;
}
public static void table1() throws Exception {
Connection conn = getConnection();
try {
java.sql.Statement stmt = conn.createStatement();
if (!doesTableExists("costs", conn)) {
String query= "CREATE TABLE costs("
+"Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
+"Name VARCHAR(60),"
+"value DOUBLE NOT NULL, "
+"driverdependent INT NOT NULL,"
+"costorpofit INT NOT NULL, "
+"fixedorvariable INT NOT NULL,"
+"driver VARCHAR(40),"
+"truck VARCHAR(40),"
+"semitrailer VARCHAR(40),"
+"Data TIMESTAMP,"
+"PRIMARY KEY (Id))";
stmt.execute(query);
}
}catch(Exception e) {System.out.println(e);}
}
static boolean doesTableExists(String tableName, Connection conn)
throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet result = meta.getTables(null, null, tableName.toUpperCase(), null);
return result.next();
}
public static void table2() throws Exception {
try {
Connection conn = getConnection();
java.sql.Statement stmt = conn.createStatement();
if (!doesTableExists("journeys", conn)) {
String query= "CREATE TABLE journeys("
+"Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
+"millage DOUBLE NOT NULL, "
+"driver VARCHAR(40),"
+"truck VARCHAR(40),"
+"semitrailer VARCHAR(40),"
+"Data TIMESTAMP,"
+"PRIMARY KEY (Id))";
stmt.execute(query);
}
}catch(Exception e) {System.out.println(e);}
}
public static void table3() throws Exception {
try {
Connection conn = getConnection();
java.sql.Statement stmt = conn.createStatement();
if (!doesTableExists("routes", conn)) {
String query= "CREATE TABLE routes("
+"millage DOUBLE NOT NULL, "
+"Name VARCHAR(40))";
stmt.execute(query);
}
}catch(Exception e) {System.out.println(e);}
}
updated
try
{
sqlite.setDbPath(dbPath);
con = sqlite.connect();
if(!con.isClosed())
{
String query="SELECT Username,Password FROM Apps WHERE Username ='"+username+"'"; // and Password='"+password+"'";
ResultSet rs = con.createStatement().executeQuery(query);
while(rs.next())
{
if(rs.getString("Username").equals(username))//confronto se Username รจ gia esistente
{
trovato = true;
risultato = "gia' presente";
}
}
if(trovato==false) {
createUsers(username,password,name,surname,email,appname,ip,authorized,token);
risultato="inserito";
}
if(con!=null)
{
con.close();
}
if(sqlite != null)
{
sqlite.close();
}
if(rs != null)
{
rs.close();
}
}
In try catch block I've open connection with database embedded but in first time i don't close all connection..
With if control the program close all open connection and works well
Update 2
Here is an abbreviated version using try-with-resource instead. Code is simpler and shorter
public String RegisterUser(... ) {
boolean trovato = false;
int authorized=0;
SqliteConnection sqlite = new SqliteConnection();
String dbPath="C:/Users/l.pellegrini/eclipse-workspace/ClayAPI_dbembedded/claydb.db";
String query="SELECT Username,Password FROM Apps WHERE Username ='"+username+"' and Password='"+password+"'";
try (java.sql.Connection con = sqlite.connect();
Statement statement = con.createStatement();
Statement updStatement = con.createStatement();
) {
ResultSet rsActiveServices = con.createStatement().executeQuery(query);
// handle result set as before
} catch(SQLException e) {
e.printStackTrace();
System.out.println("errore" + e);
}
if(trovato==false) {
createUser(username, password, name, surname, appname, email, ip)
}
return "username: " + username;
}
private createUser(String username, String password, String name, String surname, String appname, String email, String ip {
String query1="INSERT INTO Apps (Username,Password,Name,Surname,Email,AppName,Ip,Authorized,Token) VALUES ('" + username + "'," + "'" +password +"','" + name + "','" + surname + "','" +email + "','" + appname + "','"+ip+"','"+authorized+"','"+token+"')";
SqliteConnection sqlite = new SqliteConnection();
String dbPath="C:/Users/l.pellegrini/eclipse-workspace/ClayAPI_dbembedded/claydb.db";
try (java.sql.Connection con = sqlite.connect();
Statement statement = con.createStatement();) {
updStatement.executeUpdate(query1);
} catch(SQLException e) {
e.printStackTrace();
System.out.println("errore" + e);
}
}
It could very well be that your prepared statement isn't properly closed. Change
ResultSet rsActiveServices = con.createStatement().executeQuery(query);
to
statement = con.createStatement();
ResultSet rsActiveServices = statement.executeQuery(query);
where statement is declared before try
java.sql.Connection con = null;
Statement statement = null;
and then close it in your finally clause
finally
{
try
{
statement.close();
con.close();
sqlite.close();
}
Update 1
I just noticed that your are trying to close your objects twice which is wrong, remove the first set of close calls and only close within finally {} at the end.
Resolved
I do errors with open and close connection in Main.. With SQLite the connection you have to open and close everytime it's carried out a query of all type(Insert, Delete,Update ecc..)
public static void main(String[] argv) {
try {
createTable();
insertRecordIntoTable("leo","123");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void createTable() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String sequence = "CREATE SEQUENCE ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999 MINVALUE 1 CACHE 20";
String createTableSQL = "CREATE TABLE DBUSER1("
+ "USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "PASSWORD VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID) "
+ ")";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(createTableSQL);
System.out.println(createTableSQL);
// execute create SQL stetement
preparedStatement.executeUpdate(createTableSQL);
preparedStatement.executeUpdate(sequence);
System.out.println("Table \"dbuser\" is created!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
private static void insertRecordIntoTable(String username, String password) throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String insertTableSQL = "INSERT INTO DBUSER1"
+ "(USER_ID, USERNAME, PASSWORD) VALUES"
+ "(ID_SEQ.NEXTVAL,?,?)";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
// execute insert SQL stetement
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
preparedStatement.executeUpdate();
System.out.println("Record is inserted into DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
I cannot find the error when I try to create a sequence for my table.
When I try to insert some data in my table with the sequence it says it doesn't exist, but I did create it. Also I am not sure if i need a preparedStatement.setInt(1, seq_id.nextval); it gives an error but im not quite sure how I would do this
The solution might be adding the schema name (owner) before the name of sequence:
CREATE SEQUENCE some_nameOf_schema.ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999 MINVALUE 1 CACHE 20
You're preparing a statement with one SQL text, and executing the statement with two different SQL texts;
preparedStatement = dbConnection.prepareStatement(createTableSQL);
preparedStatement.executeUpdate(createTableSQL);
preparedStatement.executeUpdate(sequence);
...which is actually invalid according to the docs;
int executeUpdate(String sql)
throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Note:This method cannot be called on a PreparedStatement or CallableStatement.
What you need to do is to prepare and execute two different statements;
preparedStatement = dbConnection.prepareStatement(createTableSQL);
preparedStatement.executeUpdate();
preparedStatement = dbConnection.prepareStatement(sequence);
preparedStatement.executeUpdate();
In general, it doesn't make much sense to CREATE database objects every time your application starts up, because this is something that's usually done only once, when you install/upgrade the database/schema the application uses.
However, if you really have to do it this way, the current solution could be improved so that the following points are considered:
Only execute the CREATE statements when the objects do not yet exist in the DB. This can be done by first inspecting the USER_OBJECTS data dictionary view.
Use a plain Statement instead of PreparedStatement for executing the DDL (prepared statements are only useful for DML operations that use input variables)
Handle JDBC resources (Connection / Statement / ResultSet) concisely and safely through the try-with-resources construct
Here's how the code could look like:
// query constants
private static final String CHECK_DB_OBJECT =
"SELECT 1 FROM user_objects WHERE object_name = ?";
private static final String CREATE_SEQUENCE =
"CREATE SEQUENCE ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999" +
" MINVALUE 1 CACHE 20";
private static final String CREATE_TABLE = "CREATE TABLE DBUSER1("
+ "USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "PASSWORD VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID) "
+ ")";
/* clip the main method etc. */
/**
* Creates the table and sequence only if they do not already exist.
*/
private static void createTableAndSequenceIfAbsent() {
try (Connection dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER, DB_PASSWORD);
PreparedStatement ps = dbConnection
.prepareStatement(CHECK_DB_OBJECT)) {
if (!dbObjectExists(ps, "ID_SEQ")) {
executeDDL(dbConnection, CREATE_SEQUENCE);
}
if (!dbObjectExists(ps, "DBUSER1")) {
executeDDL(dbConnection, CREATE_TABLE);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static boolean dbObjectExists(PreparedStatement ps,
String objectName) throws SQLException {
ps.setString(1, objectName);
ResultSet rs = ps.executeQuery();
// if the #CHECK_DB_OBJECT query returned a row, the object exists
return rs.next();
}
private static void executeDDL(Connection c, String sql)
throws SQLException {
try (Statement st = c.createStatement()) {
st.execute(sql);
}
}
I am trying to write a runnable jar file that can be able to connect to 2 different databases informix old database and oracle new database. It should be able to update the new database(oracle) with the old database(informix) records.
I re-edit my java code I added separate methods for my select, update and connections I am not getting an error but its not updating my db. My select works but my update statement is not working. This is my result i get - SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE where profile_id = 102
profileid : 102
ingressflag : Y
egress_flag : Y
ceingressflag : Y
ceegressflag : Y
ResultSet not open, operation 'next' not permitted. Verify that autocommit is OFF
I am not sure how can I fixed the ResultSet not open, operation 'next' not permitted. Verify that autocommit is OFF
public class TestConnection {
static ResultSet rs;
public static void main (String[] args) throws Exception {
try{
selectRecordsIcore();
updateRecordIntoBids();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void selectRecordsIcore() throws SQLException {
Connection dbConnection = null;
Statement statement = null;
String selectTableSQL = "SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE";
try {
dbConnection = getInformixConnection();
statement = dbConnection.createStatement();
System.out.println(selectTableSQL);
// execute select SQL stetement
rs = statement.executeQuery(selectTableSQL);
while (rs.next()) {
int profileid = rs.getInt("profile_id");
String ingressflag = rs.getString("ingress_flag");
String egress_flag = rs.getString("egress_flag");
String ceingressflag = rs.getString("ce_ingress_flag");
String ceegressflag = rs.getString("ce_egress_flag");
System.out.println("profileid : " + profileid);
System.out.println("ingressflag : " + ingressflag);
System.out.println("egress_flag : " + egress_flag);
System.out.println("ceingressflag : " + ceingressflag);
System.out.println("ceegressflag : " + ceegressflag);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static void updateRecordIntoBids() throws SQLException {
Connection dbConnection = null;
Statement statement = null;
ArrayList<TempStorageRecords> updateSQL = new ArrayList<TempStorageRecords>();
while (rs.next()) {
int profileid = rs.getInt("profile_id");
String ingressflag = rs.getString("ingress_flag");
String egress_flag = rs.getString("egress_flag");
String ceingressflag = rs.getString("ce_ingress_flag");
String ceegressflag = rs.getString("ce_egress_flag");
String updateTableSQL = "UPDATE traffic_profile SET ingress_flag = " + ingressflag
+ " ,egress_flag = " + egress_flag
+ " ,ce_ingress_flag = " + ceingressflag
+ " ,ce_egress_flag = " + ceegressflag
+ " WHERE profile_id = " + profileid + ";";
try {
dbConnection = getOracleConnection();
statement = dbConnection.createStatement();
System.out.println("updateTableSQL 1 :" + updateTableSQL);
// execute update SQL stetement
statement.execute(updateTableSQL);
System.out.println("updateTableSQL 2: " + updateTableSQL);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
}
public static Connection getOracleConnection() throws SQLException {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#oracle_host:1521:BIDS";
String username = "username";
String password = "password";
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // load Oracle driver
Connection dbConnection = null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
url, username,password);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
public static Connection getInformixConnection() throws SQLException {
String driver = "com.informix.jdbc.IfxDriver";
String url = "jdbc:informix-sqli://informix_host:1615/icore:INFORMIXSERVER=icit";
String username = "user";
String password = "pass";
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // load Informix driver
Connection dbConnection = null;
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
url, username,password);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}
At first try to export data from source database into text file.
Your code uses hard coded column names, but I think it could read table names to export from some config file and column names from metadata from SELECT * FROM [table_name]. In JDBC there is getMetaData() for RecordSet. Use it.
When you export data into text files without problems you can do the next step: import such data directly from the source database to the destination database.
For destination database create prepareStatement with:
'INSERT INTO ' + table_name_dest + ' (' + column_names +') VALUES ('+ question_marks + ')'
(there question_marks are '?' chars which maps to columns).
Then for each record from source table and for each record (row) do:
insert_stmt.setObject(i, rs_in.getObject(i))
For big tables you can also use setFetchSize() and addBatch()/executeBatch()
I am trying to inserting the data into the table using ms access 2007 but getting the exception "java.sql.SqlException: no data found"
My data souce name is employee
import java.sql.*;
class AccessDatabase
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection ("jdbc:odbc:employee");
Statement st = con.createStatement();
String name = "roseindia";
String address = "delhi";
int i = st.executeUpdate("insert into user(name,address) values
('" + name + "','" + address + "')");
System.out.println("Row is added");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I think you don't have a database created. Following code should work:
import java.sql.*;
class ExecuteSqlQuery {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
String str = "CREATE TABLE user(id INTEGER, " + "name VARCHAR(25), address VARCHAR(100), primary key(id))";
st.executeUpdate(str);
System.out.println("Table is created into the database.");
st.executeUpdate("insert into user(id,name,address) values(1111,'roseindia','Rohini,Delhi')");
System.out.println("Row is inserted.");
st.close();
con.close();
}
catch (Exception ex) {
System.out.println("Unable to connect to database.");
}
}
}