Advertisement
Guest User

first jdbc

a guest
Dec 5th, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. package MyDB;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.SQLException;
  7.  
  8. public class Tester {
  9.     //to create a connection to our Data Base
  10.     private static Connection db;
  11.     //will convert our SQL request to a statement that the DB will recognize
  12.     private static PreparedStatement statement;
  13.     //address of our mysql
  14.     //final static String URL = "jdbc:mysql://127.0.0.1:3306/";
  15.     final static String URL = "jdbc:mysql://localhost/";
  16.     final static String OLDJDBC = "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
  17.     //name of the data base
  18.     final static String DB_NAME = "wtf";
  19.     //name of user (in our case administrator)
  20.     final static String DB_USER = "root";
  21.     //administrator password
  22.     final static String DB_PASS = "";
  23.  
  24.     public static void main(String[] args) throws SQLException {
  25.         //create our connection string
  26.  
  27.         //creating a connection to our data base, using our new library
  28.         db = DriverManager.getConnection(URL+DB_NAME+OLDJDBC,DB_USER,DB_PASS);
  29.  
  30.         //create table for the first time if it's not exists
  31.         createTable();
  32.     }
  33.  
  34.     private static void createTable() {
  35.         //create SQL statment
  36.         String sql = "CREATE TABLE IF NOT EXISTS drugs "+
  37.                 "(id INT PRIMARY KEY AUTO_INCREMENT, "+
  38.                 "name VARCHAR (16) NOT NULL);";
  39.         try{
  40.             //prepare a SQL command
  41.             statement = db.prepareStatement(sql);
  42.             //execute the SQL command
  43.             statement.execute();
  44.             System.out.println("Table was created");
  45.         } catch (SQLException err){
  46.             System.out.println(err.getMessage());
  47.         }
  48.  
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement