(Core-JAVA) MySQL JAVA

Example of MySQL JAVA


1. Download MySQL and run the server.

2. Create one table in one database.

3. Download JAVA jdbc jar, ex, mysql-connector-java-5.1.25, and import it in the JAVA project.

4. The JAVA example as follows,


package jdbc;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySQLConnection {
private static MySQLConnection connection;
public static MySQLConnection getInstance() {
if (connection != null) {
return connection;
} else {
return new MySQLConnection();
}
}
private MySQLConnection() {}
private final static String username = "palmer";
private final static String pwd = "123456";
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
private Connection conn = null;
private Statement stmt = null;
public boolean makeConnection() {
stmt = null;
// STEP 1: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
// STEP 2: make a connection to the database
conn = DriverManager.getConnection(DB_URL, username, pwd);
stmt = conn.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public void releaseConnection() {
try {
// STEP 4: release connection and statement.
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet query(String sqlStr) {
try {
// STEP 3: do database operations.
ResultSet set = stmt.executeQuery(sqlStr);
while (set.next()) {
int id = set.getInt(1);
String name = set.getString(2);
System.out.println(id + "  " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void main(String args[]){
MySQLConnection connection = MySQLConnection.getInstance();
if(connection.makeConnection()){
connection.query("select * from test_1;");
connection.releaseConnection();
}
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值