I'm trying to edit an MS Access database using some Java code (running NetBeans 7.2.1). I set up the data source and linked it to my database ProjectDatabase using the ODBC tool and named the data source DB, then i run the following code:
import java.sql.*;
public class NewMain {
public static void main(String[] args) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:DB");
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);
}
}
}
The code runs without and error and returns the "Row is added" message. The problem is that when I go back to view the database the changes have not taken effect. I have tried this with a code for deleting the data, also to no effect. Has anybody had this problem and knows how to solve it?
I'm running Windows 7 64-bit, Microsoft Office 64-bit with all the 64-bit drivers and I have been unable to find any mention of this problem through web searches.
Thanks in advance for any help =)
First of all you are not closing the connection, so that is one problem. Also change your code to:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:DB");
Statement st=con.createStatement();
con.setAutoCommit(false); //Notice change here
String name="roseindia";
String address="delhi";
int i=st.executeUpdate("insert into user(name,address) values('"+name+"','"+address+"')");
con.commit(); //Notice change here
System.out.println("Row is added");
con.close(); //Notice change here
This will commit the changes to access database, so now you should be able to see data in MS Access.
Read here to know more about best practices for Closing and Releasing JDBC resources
Related
I have looked at every possible answer on this site, nothing quite covers the issue.
I followed a tutorial and tried using the Firefox SQLite Manager AND using the SQLite3 shell to create the same database.
public class DBConnector {
static Connection conn = null;
public static Connection connect()
{
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\John\\Desktop\\database.db");
return conn;
}
catch(Exception e){
e.printStackTrace(System.out);
return null;
}
}
}
Whenever I run this i get:
java.sql.SQLException: path to 'C:\Users\John\Desktop\database.db': 'C:\Users\John\Documents\NetBeansProjects\JBook\C:' does not exist
I'm new enough to this to where I have no idea what the issue is.
Any help is greatly appreciated. And yes, I have looked at all of the other questions posted and tried using their answers, to no avail.
Thanks again
EDIT: A couple of the possible answers already listed have included to change the .db extension to .sqlite
This did NOT work.
Another simply showed how to use an absolute path, once again, I had that covered and it didn't work.
Another talked about JUnit test and some issue they were having which was irrelevant to what I am doing
Finally got the issue:
Copy the path you specified in notepad++ and set encoding to ansi and you will see some special character before C: which is causing issue .
conn = DriverManager.getConnection("jdbc:sqlite:‪C:\\Users\\ravi\\Desktop\\database.db");
conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\ravi\\Desktop\\database.db");
Hi I am new enough to java and I am trying to create a connection from it to my sql database. using Netbeans I managed to set up a connection easily enough. The issue is when I try to connect using my code I get driver not found. Is there something wrong with what I have?
//function to execute the insert update delete query
public void theQuery(String query){
Connection con = null;
Statement st = null;
try{
con = DriverManager.getConnection("jdbc:oracle:thin:#redwood.ict.ad.dit.ie:1521:pdb12c.ict.ad.dit.ie", "eocribin","");
st = con.createStatement();
st.executeUpdate(query);
JOptionPane.showMessageDialog(null,"Query Executed");
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
you have to add oracle thin driver into your projects library and then restart the IDE to take notice of changes. Make sure that oracle's server is running when you run this code. Also check the username and password.
Java Persistence in netbeans is a much better option then using Oracle thin driver in your code. Because it saves much of your time typing and harcoding. JPA(Java Persistence API) allows you to easily add the oracle's thin driver from its menu and reduces much of your time. It is used in enterprise applications . You should try this and watch its tutorials on the following site.
These are called JPA tutorials.
http://www.programming-simplified.com
For a website developed under Tomcat, I connect my program to a database neo4j. Connection is done through jdbc.
My program is right now local, and the database is on a remote server.
When I start Tomcat, it first check if specifics nodes are presents, and if not, it creates them.
There are about 135 nodes.
Problem : After about ten, the program stops, and stay in something like an infinite loop.
I assume I should close something, but what?
Here is my code :
private ResultSet sendCommand(String command) throws SQLException
{
try(Statement statement = _neo4jConnection.createStatement())
{
return statement.executeQuery(command);
}
}
and a function to call this code (all functions are based on the same structure)
public static Long createNode(NodeLabel labelName)
{
try
{
ResultSet rs = getInstance().sendCommand("CREATE (n:"+labelName+") RETURN id(n)");
Long result= rs.next()?rs.getLong("id(n)"):null;
rs.close();
return result;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
in my latest experiment I reused the same statement multiple times, not sure that is the best way but it seems to work good, too.
https://github.com/peterneubauer/blogs/tree/master/csv_jdbc, code at https://github.com/peterneubauer/blogs/blob/master/csv_jdbc/src/test/java/org/neo4j/jdbctest/JDBCTest.java
The only solution I found was to regularly disconnect and reconnect to the database (After about 20 statements). This is awful, but it works.
Well, however, I gave up with jdbc for neo4j, too much issues, and catastrophical performances (about 1s to get one simple data), what occures still more issues!
Anyway, Thanks for your help
Niko
I am beginner in Java application programming.
I've created a database application in Java. I use an MS access database with the JDBC-ODBC driver. My application's create-connection code is below:
private void connection() {
try {
String driverurl = "jdbc:odbc:dharti_data";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(driverurl,"","");
} catch (SQLException e) {
JOptionPane.showMessageDialog(frm,e.getSQLState(),"Database Access Error",JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage(),"Database Access Error",JOptionPane.ERROR_MESSAGE);
}
}
This code works perfectly, but this code uses a datasource name I declared in Control Panel > Administrative Tools > Data Sources (ODBC) > System DSN > Add Data Source, with a Microsoft Access Driver (*.mdb).
But when I run the application on another PC, it can't run and instead it generates a database error.
I know that I can declare a driver in Data Sources (ODBC) > System DSN, and then it will run. But I don't want to do this on every machine I run my application on. My application should be able to pick up the database connection automatically. How can I make my application not require a data-source name?
String filename = "C:/Lab/northwind.mdb"; // this the path to mdb file
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end
// now we can get the connection from the DriverManager
Connection con = DriverManager.getConnection( database ,"","");
Im not sure if I got this, but are you shipping the jdbc driver along with your application? It has to be in your classpath and needs to be deployed with your application.
You will have to programmatically modify these registry sections:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI and
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC
Ice Engineering offer a public domain api that allows you to do that. Beside jars it has a DLL that you have to ship with your application. It is fairly straight forward and will work.
In order to get a better idea of what you have to do, use regedit in order to see the values before installing anything, then install an ODBC database manually, finally compare the new values with the old.
I used the sun.jdbc.odbc.JdbcOdbcDriver to connect to a MS Access database. Have that in the same directory as the class file and it should work. Although it should come already installed in the Java SDK.
This is a sample of a practice program I made a while ago.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded");
// Establish a connection
Connection connection = DriverManager.getConnection
("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=(MS ACCESS DATABASE DIRECTORY)");
System.out.println("Database connected");
// Create a statement
Statement statement = connection.createStatement();
// Execute a statement
ResultSet resultSet = statement.executeQuery
("select f_name, l_name from Test where f_name = 'Luke'"); // For example
// Iterate through the result and print the results
while (resultSet.next())
System.out.println(resultSet.getString(1) + "\t" + resultSet.getString(2) );
I have a problem connecting to MS Access and MySQL using Java. My problem is that I cannot find the driver for MySQL. Here is my code:
<%# page import="java.sql.*" %>
<%
Connection odbcconn = null;
Connection jdbcconn = null;
PreparedStatement readsms = null;
PreparedStatement updsms = null;
ResultSet rsread = null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //load database driver
odbcconn = DriverManager.getConnection("jdbc:odbc:SMS"); //connect to database
readsms = odbcconn.prepareStatement("select * from inbox where Status='New'");
rsread = readsms.executeQuery();
while(rsread.next()){
Class.forName("com.mysql.jdbc.Driver");
jdbcconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bakme", "root", ""); //connect to database
updsms = jdbcconn.prepareStatement("insert into inbox(sms,phone) values (?,?)");
updsms.setString(1, rsread.getString("Message"));
updsms.setString(2, rsread.getString("Phone"));
updsms.executeUpdate();
}
%>
Thus, you get a ClassNotFoundException on the MySQL JDBC driver class? Then you need to put the MySQL JDBC driver JAR file containing that class in the classpath. In case of a JSP/Servlet application, the classpath covers under each the webapplication's /WEB-INF/lib folder. Just drop the JAR file in there. Its JDBC driver is also known as Connector/J. You can download it here.
That said, that's really not the way how to use JDBC and JSP together. This doesn't belong in a JSP file. You should be doing this in a real Java class. The JDBC code should also be more robust written, now it's leaking resources.
BalusC is spot on: this is not the way you should write something like this.
Connection, Statement, and ResultSet all represent finite resources. They are not like memory allocation; the garbage collector does not clean them up. You have to do that in your code, like this:
// Inside a method
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
try
{
// interact with the database using connection, statement, and rs
}
finally
{
// clean up resources in a finally block using static methods,
// called in reverse order of creation, that don't throw exceptions
close(rs);
close(statement);
close(connection);
}
But if you do decide to move this to a server-side component, you're bound to have huge problems with code like this:
while(rsread.next())
{
Class.forName("com.mysql.jdbc.Driver");
jdbcconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bakme", "root", ""); //connect to database
updsms = jdbcconn.prepareStatement("insert into inbox(sms,phone) values (?,?)");
updsms.setString(1, rsread.getString("Message"));
updsms.setString(2, rsread.getString("Phone"));
updsms.executeUpdate();
}
Registering the driver, creating a connection, without closing it, and repeatedly preparing a statement inside a loop for every row that you get out of Access shows a serious misunderstanding of relational databases and JDBC.
You should register the driver and create connections once, do what needs to be done, and clean up all the resources you've used.
If you absolutely MUST do this in a JSP, I'd recommend using JNDI data sources for both databases so you don't have to set up connections inside the page. You should not be writing scriptlet code - better to learn JSTL and use its <sql> tags.
You can use this link to download the MySql Driver. Once you download it, you need to make sure it is on the class path for the web server that you are using. The particulars of configuring JDBC drivers for a server vary from server to server. You may want to edit your question to include more details to get a better answer.