//记得引入驱动包!!!
package DatabaseT;
import java.sql.*;
import com.mysql.jdbc.Connection;
public class MysqlDemo {
static final String DB_URL = “jdbc:mysql://localhost:3306/ch09?useSSL=false”;
// MySQL的JDBCURL编写方式:jdbc:mysql://主机名称:连接端口/数据库的名称
static final String USER = “root”;
static final String PASS = “root”;
public static void main(String[] args) throws SQLException,Exception{
Connection conn = null;
PreparedStatement stat = null;
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 创建链接
conn = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
//stat = conn.createStatement();
stat = conn.prepareStatement(DB_URL);
String sql = "SELECT * FROM users";
ResultSet rs = stat.executeQuery(sql);
// 输出查询结果
while(rs.next()){
System.out.print(rs.getInt("id")+",");
System.out.print(rs.getString("username")+",");
System.out.print(rs.getString("password")+",");
System.out.print(rs.getString("nickname"));
System.out.print("\n");
}
// 关闭
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stat != null) {
stat.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}