第一步:导入连接mysql数据库所需要的jar包
第二步:实现一个简单的jdbc连接数据库工具类
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* JDBC连接MYSQL工具类
* yiqqin 2017.4.19
*/
public class DBHelper {
public static final String url = "jdbc:mysql://115.115.115.115/mydatabase";
public static final String name = "com.mysql.jdbc.Driver";
public static final String user = "root";
public static final String password = "root";
public Connection conn = null;
public PreparedStatement pst = null;
public DBHelper(String sql) {
try {
Class.forName(name);//指定连接类型
conn = DriverManager.getConnection(url, user, password);//获取连接
pst = conn.prepareStatement(sql);//准备执行语句
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
this.conn.close();
this.pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
第三步:写一个测试类,看连接是否成功
package demo;
import java.sql.ResultSet;
import java.sql.SQLException;
import jdbc.DBHelper;
/**
* 测试JDBC连接MYSQL
* qinyi 2017.4.19
*/
public class TestJDBC {
static String sql = null;
static DBHelper db1 = null;
static ResultSet ret = null;
public static void main(String[] args) {
sql = "SELECT imgurl,articleurl FROM imgurltable WHERE imgurltable.`index` = 6473172 and 1=1";//SQL语句
db1 = new DBHelper(sql);//创建DBHelper对象
try {
ret = db1.pst.executeQuery();//执行语句,得到结果集
while (ret.next()) {
String imgurl = ret.getString(1).substring(0, 18);
String articleurl = ret.getString(2).substring(0, 18);
System.out.println(imgurl + "\t" + articleurl);
}//显示数据
ret.close();
db1.close();//关闭连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
如果任何疑问或学习交流,请搜索公众号"老秦的快乐生活"获取我的联系方式