Skip to content

Instantly share code, notes, and snippets.

@otoo-peacemaker
Created July 21, 2019 19:51
Show Gist options
  • Save otoo-peacemaker/e583b893dc55caede91b7a6ed0a36736 to your computer and use it in GitHub Desktop.
Save otoo-peacemaker/e583b893dc55caede91b7a6ed0a36736 to your computer and use it in GitHub Desktop.
Java Database Programming
/*The following codes consists of three java classes: DBconnection class,CreateTable class, and Main JDBC class.
*The DBconnection class helps to use the Database connection anywhere your programme.
*The CreateTable also helps to access or manipualte database right in the project with less code complexity.
*The main JDBC class is where we the actual coding. Thus, The DML and DQL.
*/
//Java class : DBconnection
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* You can clean this comment
* @author Kwesi-Welbred
*/
public class DBconnection {
private static final String USERNAME = "KwesiWelbred";
private static final String PASSWORD = "dbpassword";
private static final String CONN = "jdbc:mysql://localhost/librarymanagement";
//class method for the connection
public static Connection getConnection() throws SQLException{
System.out.println("Connecting Database....");
return DriverManager.getConnection(CONN, USERNAME, PASSWORD);
}
}
//Create new Java class: Creating Table
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author Kwesi-Welbred
*/
public class addbook {
public static void getbook(ResultSet rs) throws SQLException {
while (rs.next()) {
StringBuilder buffer = new StringBuilder();
buffer.append("id ").append(rs.getString("id")).append(" ");
buffer.append(rs.getString("title")).append(" ");
buffer.append(rs.getString("author")).append(" ");
buffer.append(rs.getString("publisher")).append(" ");
buffer.append(rs.getInt("copies")).append(" ");
buffer.append(rs.getString("subject")).append(" ");
System.out.println(buffer.toString());
}
}
}
// class :Main.java
import JavaDBC.libraryTables.addbook;
import java.sql.*;
/**
*
* @author Kwesi-Welbred
*/
public class MainJDBP {
public static void main(String[] args) throws SQLException {
//class.forName("com.mysql.jdbc.Driver");
//DQL & DML GOES HERE
String update = "insert into addbook(id,title,author,subject,publisher,copies)values('lbs6','VB','Bill Gate','programming','Microsoft',10)";
String query = "select *from addbook ";
try (
Connection con = DBconnection.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);) {
System.out.println("Database Connected");
/* uncomment this code if you want do DML
*int count = stmt.executeUpdate(update);
*System.out.println(count + "row affected");
*/
addbook.getbook(rs);
} catch (SQLException e) {
System.err.println(e);
}
}
}
@otoo-peacemaker
Copy link
Author

you can email me for better clarification. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment