1、导入jar包
mysql-connector-java-5.1.5-bin.jar
2、如何访问Java连接MySQL数据库。
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
// URL指向要访问的数据库名myschool
String url = "jdbc:mysql://localhost:3306/myschool";
//Mysql配置时的用户名
String user = "root";
//Mysql配置时的密码
String password = "123456";
//连接数据库
Connection conn = DriverManager.getConnection(url, user, password);
//st用来执行sql语句
Statement st = conn.createStatement();
//要执行的拼装的sql语句(student为表名)
String sql = "SELECT * FROM student";
//获得结果集
ResultSet rs = st.executeQuery(sql);
//遍历结果集
while (rs.next()) {
//接收数据
rs.getString("Sno")//Sno为student表里的列名(以下相同)即属性
rs.getString("Sname")
rs.getInt("Sage")
rs.getString("Sex")
rs.getString("SD")
rs.getString("Email")
rs.getString("Tel")
}
//关闭rs,st,conn
rs.close();
st.close();
conn.close();