How to create initializeDB() method for java database - java

I am working on a Java project for class and have not worked much with incorporating databases into Java. I can't find much on the initializeDB() method, but if I could get some help I would really appreciate it.
Below is the code being used for the intializeDB() method:
private void initializeDB() {
try {
// Load the JDBC driver
System.out.println("Driver loaded");
// Establish a connection
System.out.println("Database connected");
// Create a statement
// Create a SQL Query string
// Execute the query to create a recordset
}
catch (Exception ex) {
ex.printStackTrace();
}
}

check out JDBC Tutorial

You might also find some sample code on the website for your database vendor. For example, if you are using MySQL, you might find these examples helpful.

Related

statement.executeQuery( ) returns nullpointer exception for Netbeans but works fine for Intellij Idea [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am new to Netbeans and I decided to use Swing Forms with Java MySQL CRUD operations I have tested in Intellij before. At this point, while applying MySQL snippet as you can see below. I got "Nullpointer Exception" for the line "rs = statement.executeQuery("SELECT * FROM cities");". I also tested whether there is any database connection establishment issues with try catch phrases using "e.getMessage()" and "e.getErrorCode()" for SQLException and ClassNotFound cases but no exception returned. I have been trying understand the reason but I am having a trouble to figure it out. I will be appreciated for any help. Thanks in advance.
private static void TestWorldTable(){
//connection presets
String url = "jdbc:mysql://localhost:3306/world";
ResultSet rs = null;
try {
//connection establishment
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, null, null);
Statement statement = con.createStatement();
rs = statement.executeQuery("SELECT * FROM cities");
}
catch (ClassNotFoundException| SQLException ignored){}
try {
//record retrieval observation for CRUD
while(rs != null && rs.next()){
System.out.println(rs.getString("name"));
}
catch (SQLException ignored) {}
}
Edit: The problem has been solved. The issue is solved after creating a new library and adding mysql_connector to the classpath of that library, adding dependencies of that mysql_connector to pom.xml then changing database url to ssl and servertimezone dependent version as
"jdbc:mysql://localhost:3306/< DatabaseName >?useSSL=false&serverTimezone=UTC"
catch (ClassNotFoundException| SQLException ignored){}
Don't do this. You're asking java to take useful information about problems and just toss it in the toilet, and now you're on SO asking, bewildered, why your code isn't work. Do not ignore exceptions unless you really, really, really know what you are doing. The right ¯\(ツ)/¯ I dunno what to do exception handler is this:
catch (SQLException e) {
throw new RuntimeException("uncaught", e);
}
though, even better is to just declare your methods to 'throws' whatever seems relevant, and certainly SQLException is relevant here.
So what's the problem?
When running on the command line, the MySQL jdbc driver isn't on the classpath. You don't need that Class.forName bit, by the way. java will figure it out on its own. Make sure you use the -cp option to add that jdbc driver.

Connection to oracle database

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

How do I edit MS Access database using Java (NetBeans)

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

How to register dbus object using dbus-java?

I'm trying to register object on dbus using dbus-java from org.freedesktop. According to documentation such operation requires: creating DBusConnection, creating object and calling method exportObject on DBusConnection.
My Code:
DatabaseAccessImpl dbAccess = new DatabaseAccessImpl();
System.out.println("Object created.");
System.out.println("Trying to connect session bus");
try {
conn = DBusConnection.getConnection(DBusConnection.SESSION);
} catch(DBusException ex) {
ex.printStackTrace();
}
System.out.println("Connected to session bus.");
System.out.println("Trying to register dbus object");
try {
conn.exportObject("/obj/path", new DatabaseAccessImpl());
} catch (DBusException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
where:
DatabaseAccessImpl is implementation of interface created automatically by CreateInterface (xml worked fine while using with c++ (qt)).
dbAccess will send on dbus some data (mostly ints) from database. It all work good in Qt but I have to reimplement it in java (not my language).
For using dbus-java you have to install libmatthew-debug and execute program with
-Djava.library.path=/usr/lib/jni
I'm working on Linux Mint.
Two things:
You need to register a bus name first, i.e. conn.requestBustName("com.example")
DatabaseAccessImpl needs to implement an interface which extends DBusInterface.
Here's a tutorial that I made a while ago with code that may help you understand what's going on.

Use Database in java application

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) );

Categories

Resources