1 package com.tn.mysqlconnection; 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 public class MySQLConnection { 10 private static final String DBDRIVER = "com.mysql.jdbc.Driver"; 11 private static final String DBURL = "jdbc:mysql://localhost:3306/" 12 + "[email protected][email protected]=true&characterEncoding=UTF8"; 13 private static final String URL = "jdbc:mysql://localhost:3306/db_tuniu"; 14 private static final String DBUSER = "xiongjiawei"; 15 private static final String PASSWORD = "Tuniu520"; 16 private Connection conn = null; 17 18 public MySQLConnection() { 19 try { 20 Class.forName(DBDRIVER); 21 this.conn = DriverManager.getConnection(URL, DBUSER, PASSWORD); 22 } catch (Exception e) { 23 e.printStackTrace(); 24 } 25 } 26 27 public Connection getConnection() { 28 return this.conn; 29 } 30 31 public void close() { 32 if (this.conn != null) { 33 try { 34 this.conn.close(); 35 } catch (SQLException e) { 36 e.printStackTrace(); 37 } 38 } 39 } 40 41 public static void main(String[] args) { 42 MySQLConnection mySQLConnection = new MySQLConnection(); 43 Connection conn = mySQLConnection.getConnection(); 44 String sql = "INSERT INTO student(name) VALUES(?)"; 45 try { 46 PreparedStatement statement = conn.prepareStatement(sql); 47 // ResultSet resultSet=statement.executeQuery(); 48 statement.setString(1, "赵六子"); 49 System.out.println(statement.executeUpdate()); 50 conn.close(); 51 } catch (SQLException e) { 52 e.printStackTrace(); 53 } 54 } 55 }
时间: 2024-10-11 07:10:22