1 package cn.edu.njupt.dbconnection; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 9 10 public class DatabaseConnection {11 12 private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";13 private static final String DBURL = "jdbc:mysql://localhost:3306/jdbcdemo";14 private static final String DBUSER = "root";15 private static final String DBPASSWORD = "mysqladmin";16 private Connection conn;17 18 public DatabaseConnection(){19 try {20 Class.forName(DBDRIVER);21 this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);22 } catch (ClassNotFoundException e) {23 e.printStackTrace();24 } catch (SQLException e) {25 e.printStackTrace();26 }27 }28 29 public Connection getConnection(){30 return this.conn;31 }32 33 public void close(){34 if(this.conn != null){35 try {36 this.conn.close();37 } catch (SQLException e) {38 e.printStackTrace();39 }40 }41 }42 public static void main(String[] args) {43 String sql = "create table student(id varchar(5),name varchar(20),primary key(id));";44 try {45 PreparedStatement pstmt = new DatabaseConnection().getConnection().prepareStatement(sql);46 int result = pstmt.executeUpdate();47 if(result != -1){ //创建成功48 System.out.println("数据库 创建 成功");49 String sql1 = "insert into student(id,name) values(1,'张三')";50 int r1 = pstmt.executeUpdate(sql1);51 System.out.println("数据插入 r1 成功");52 String sql2 = "insert into student(id,name) values(2,'李四')";53 int r2 = pstmt.executeUpdate(sql2);54 System.out.println("数据插入 r2 成功");55 String sql3 = "select * from student";56 ResultSet rs = pstmt.executeQuery(sql3);57 System.out.println("学号\t姓名");58 while(rs.next()){59 System.out.println(rs.getString(1)+"\t"+rs.getString(2));60 }61 }62 new DatabaseConnection().close();63 } catch (SQLException e) {64 e.printStackTrace();65 }66 }67 68 }