java类测试MySQL数据库连接数据获取:
jar包自己下载,直接代码:
package com.hsc.data;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DataServer {
private static final String URL="jdbc:mysql://localhost:3306/hscdemo";
private static final String USER="root";
private static final String PASSWORD="hsc201751";
private static Connection conn=null;
public static void main(String[] args) {
conn();
}
/**
* Statement 和 PreparedStatement之间的关系和区别.
关系:PreparedStatement继承自Statement,都是接口
区别:PreparedStatement可以使用占位符,是预编译的,批处理比Statement效率高
*/
public static void conn() {
try {
// 1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 2.获得数据库链接
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
// 3.通过数据库的连接操作数据库,实现增删改查(使用Statement类)
String id="1";
//预编译PreparedStatement
String sql="select * from hscdata where id=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, id);
ResultSet rs = statement.executeQuery();
//Statement
// String sql="select * from customer where loginName='"+loginName+"'";
// Statement statement = conn.createStatement();
// ResultSet rs = statement.executeQuery(sql);
// 4.通过数据库的连接操作数据库,处理数据库的返回结果(使用ResultSet类)
while (rs.next()) {
System.out.println(rs.getString("id") + " " + rs.getString("telephone"));
}
// 关闭资源
conn.close();
rs.close();
statement.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
}
//对外提供一个方法来获取数据库连接
public static Connection getConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
return conn;
}
}