首页 > 代码库 > 【java】JDBC连接MySQL
【java】JDBC连接MySQL
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 + "user=xiongjiawei@password=Tuniu520@useUnicode=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 }
【java】JDBC连接MySQL
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。