展开全部
假设你的用户名636f70793231313335323631343130323136353331333363383366和密码都是root,你看下吧,在运行之前要先导入连接的那个jar文件import java.sql.*;
public class TestConnectMySQL {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance(); // new一个Driver
conn = DriverManager.getConnection("jdbc:mysql://localhost/A?" //连接MySQL 不理解就记住
+ "user=root&password=root");
stmt = conn.createStatement(); //通过连接创建(createStatement)一个语句对象,不是new
rs = stmt.executeQuery("select * from pers"); //执行查询,返回一个结果集rs相当于一个游标
while (rs.next()) { //循环取得结果集(遍历)
System.out.println(rs.getString("b") + " " //把某一字段的内容 当成一个字符串拿出来,
+ rs.getString("c") + " " //也可以用其它的,比如rs.getInt("");等
+ rs.getString("d"));
}
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally { //不要忘了关闭
try {
if (conn != null) {
conn.close();
conn = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (rs != null) {
rs.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}