SQL statements in Java function - java

I am using Java and MySQL.
I have two sql statement in two separate function, one create database, another create tables.
I try to write try & catch exception block in each function, it works, like code below.
public class j_sql1 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost";
static final String DB_URL2 = "jdbc:mysql://localhost/zxc";
static final String USER = "root";
static final String PASS = "";
static Connection conn = null;
static Statement stmt = null;
public static void create_db()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE DATABASE zxc";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2){}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
public static void create_tables ()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL2, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE TABLE ABC("+
"abc_ID int NOT NULL AUTO_INCREMENT,"+
"abc_Name varchar(50),"+
"PRIMARY KEY (abc_ID))";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2)
{}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
public static void main(String[] args)
{
create_db();
create_tables();
}
}
But what if only one catch exception block in the main for my two try blocks in the two functions something like the code below, possible?
public class j_sql1 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost";
static final String DB_URL2 = "jdbc:mysql://localhost/zxc";
static final String USER = "root";
static final String PASS = "";
static Connection conn = null;
static Statement stmt = null;
public static void create_db()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE DATABASE zxc";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
}
public static void create_tables ()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL2, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE TABLE ABC("+
"abc_ID int NOT NULL AUTO_INCREMENT,"+
"abc_Name varchar(50),"+
"PRIMARY KEY (abc_ID))";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
}
public static void main(String[] args)
{
try
{
create_db();
create_tables();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2)
{}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
}
And why the variable like Connection, Statement and the functions have to be declared to static?
Thank You.

In the static main, there is no object instance of the class j_sql1. Hence only static fields may be read.
You should do
Naming convention the same as 99.9 % of java users:
class JSql1
void createDB()
void createTables()
Instantiate an object, and call functions on it:
... main(...) {
JSql1 app = new JSql1();
try {
app.openConnection();
app.createDB();
app.createTables():
} catch (SQLException e) {
Logger.getLogger(JSql1.class.getName()).log(Level.FATAL, "...", e);
} finally {
app.close();
}
When createDB fails, there is no need to continue, hence createDB should throw the
exception.
Also the functions are uaseful inside a single connection, so create the connection
separately.
Design decision, but at least for statements declare all as locally as possible
Especially try-with-resource for automatically closing helps here
class JSql1;
Connection conn;
void createTables() throws SQLException {
try (Statement stmt = conn.createStatement()) {
String sql = "CREATE TABLE ABC(" +
"abc_ID int NOT NULL AUTO_INCREMENT," +
"abc_Name varchar(50)," +
"PRIMARY KEY (abc_ID))";
stmt.executeUpdate(sql);
}
}

Related

JDBC connection in Java with Eclipse ( when a method calling a method)

I'm trying to connect to my DB using JDBC. I wanted to make a method for connection and another method for selecting data. I am getting a red line in Eclipse on the 'Connection con = connectDB();' part. ( See also attached) Cany anyone give me advice?
public class DBJdbc {
//Statement stmt = null;
// connecting to DB
public void connectDB() {
//Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
// a method for selecting DB
public static void select() {
//connectDB();
String sql = "SELECT * from SAC_SUR";
try(Connection con = connectDB(); // I'm getting a red line here)
PreparedStatement pstmt = con.prepareStatement(sql)){
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println("Id = " + id + "name = " + name);
} //while
} catch(SQLException e) {
System.out.println(e.getMessage());
}
}
red line here!!!
connectDB() method is of void type and not returning anything but when you are calling the method, you are assigning it to variable con. So you need to change the return type of connectDb to the Connection type.
public Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
You are trying to call non-static method into the static area, which is not allowed in Java. So I made this method static and returning the database connection.
Please update the below method into your code. It will resolve your problem.
public static Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "", "");
} catch(SQLException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}

Missing IN or OUT parameter at index:: 1, trying to insert data in database

private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DB_CONNECTION = "jdbc:oracle:thin:#localhost:1521:XE";
private static final String DB_USER = "scott";
private static final String DB_PASSWORD = "tiger";
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 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();
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"
+ "(?,?,?)";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
// execute insert SQL stetement
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'm pretty sure the problem is when I try to insert data into the database but I cannot figure out why is this occurring. If there is anyone that can find my problem, please fill free to help me. Thank you.
Before you call preparedStatement.executeUpdate(); you need to set the parameter values using setXXX() method, like below:
preparedStatement.setInt(1, SOME_ID);
preparedStatement.setString(2, username);
preparedStatement.setString(3, password);
Those are the statements that substitutes the value of the parameters in the query.

Trying to connect to a database in Eclipse ee

I have been trying this for a few hours now but with no success. I downloaded the JDBC driver and it shows that it is one of my referenced libraries under my Package Explorer in Eclipse but every time I try to run my code I get errors. My database is fine as I can change it and view it from the MySQL Command Line Client.
I actually followed a guides directions on how to do it, only replacing the information from their database to information about mine.
import java.sql.*;
public class FirstExample {
//JDBC Driver Name and Database URL
final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final static String DB_URL = "jdbc:mysql://localhost/test_database";
//Database Credentials
static final String USER = "user_one";
static final String PASS = "User_one_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
//Open a Connection
System.out.println("Connecting to the Database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Execute a Query
System.out.println("Creating Statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM user";
ResultSet rs = stmt.executeQuery(sql);
//Extract Data from Result Set
while (rs.next()) {
//Retrieve by Column Name
int id = rs.getInt("id");
String first = rs.getString("name");
//Display Values
System.out.print("ID: " + id);
System.out.println("Name: " + first);
}
//Clean Up Environment
rs.close();
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 (Exception se) {
se.printStackTrace();
}//End Finally Try
}//End Try
System.out.println("Goodbye!");
}//End Main
}//End First Example
Here is the error I get http://pastebin.com/hLSxV3aq

Getting null pointer exception in JDBC(mySql) program

I checked everything like username, password, db_url, table name, etc but still I get this output---connecting to database
creating statement
java.lang.NullPointerException
here is my code, (I'm using eclipse Kepler EE and MySQL 5.6.17.0)
import java.sql.*;
public class Demo {
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/sample";
static final String USER="root" ;
static final String PASS="root";
public static void main(String[] args)
{
Connection conn=null;
Statement stmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("connecting to database");
conn=DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("creating statement");
String sql="select * from sample";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
int eid=rs.getInt("id");
String ename=rs.getString("name");
System.out.print(eid+"\t");
System.out.print(ename);
System.out.println("");
}
rs.close();
stmt.close();
conn.close();
}catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
if(stmt!=null)
{
stmt.close();
}
}catch(Exception e)
{
System.out.println(e);
}
try
{
if(conn!=null)
{
conn.close();
}
}catch(Exception e)
{
System.out.println(e);
}
}
}
}
I don't think your statement is set. It is always null.
I think you should use this:
stmt = conn.createStatement( );
You didnt create stmt object
stmt = conn.createStatement( );
You have to add above line before this line ResultSet rs=stmt.executeQuery(sql);
You are executing query on a null object.
So getting NPE
You set Statement stmt=null; and you never initialize it later.

database createstatement can't be reached

Hello I have this class that contains a actionPerformed to perform a query it looks like this
MysqlConnect db = new MysqlConnect();
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == openKnop) {
try {
db.connectToAndQueryDatabase("test", "root", "root");
System.out.println("connection established");
Statement st = db.createStatement();
String query = "SELECT id, name, job_id, location FROM person WHERE name = 'Tom Swift'";
st.executeQuery(query);
System.out.println("Selected query succesfull");
} catch (SQLException e1) {
e1.printStackTrace();
}
finally {
db.closeCon();
System.out.println("connection closed");
}
}
and my MysqlConnect(); class looks like this
public class MysqlConnect{
protected Connection con;
public void connectToAndQueryDatabase(String database, String username, String password) throws SQLException {
con = null;
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/" + database,
username,
password);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void closeCon() {
con = null;
}
}
but the problem is at the line
Statement st = db.createStatement();
it doesn't work like i've expected. I'm getting a undefined error.. how can I solve this?
The error says that db an reference of 'MysqlConnect ' doesn't have createStatement method. you need a Connection object. Make your connectToAndQueryDatabase to return Connection object
public Connection connectToAndQueryDatabase(String database, String username, String password) throws SQLException {
//your code
return con;
}
and :
Connection conn = db.connectToAndQueryDatabase("test", "root", "root");
System.out.println("connection established");
Statement st = conn.createStatement();
String query = "SELECT id, name, job_id, location FROM person WHERE name = 'Tom Swift'";
st.executeQuery(query);

Categories