javaJDBC连接MySQL

Posted xiongjiawei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javaJDBC连接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             + "[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 }
View Code

 

以上是关于javaJDBC连接MySQL的主要内容,如果未能解决你的问题,请参考以下文章

jdbc连接数据库my sql 后台java代码怎么写

JavaJDBC连接MySQL数据库,一把斗地主时间从无到有讲个通透~

JavaJDBC-使用数据库连接池技术(Druid)获取Connection对象

WEB应用程序开发---实践开发(MySQL+JavaJDBC+Ajax+JavaScript+Jquery)

java jdbc 连接数据问题

JavaJDBC编程套路