import java.sql.Connection;import java.sql.Date;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class ConnectMySQL {/*** @param args* @throws ClassNotFoundException*/public static void main(String[] args) throws ClassNotFoundException {//JDBC的一些配置String URL = "jdbc:mysql://localhost:3306/test";String driverName = "com.mysql.jdbc.Driver";String sql = "select * from students";String userName = "root";//rootString password = "123456";//123456Connection conn = null;Class.forName(driverName);//jdbc4.0 后无需使用这句进行驱动注册操作try {conn = DriverManager.getConnection(URL,userName,password);Statement statement = conn.createStatement();ResultSet resultSet = statement.executeQuery(sql);// id | stuno | name | gender | birthdate | majorwhile(resultSet.next()){int id = resultSet.getInt("id");String stuno = resultSet.getString("stuno");Date date = resultSet.getDate("birthdate");System.out.print("id="+id+" stuno="+stuno+" birthdate="+date);}} catch (SQLException e) {e.printStackTrace();}finally{if(conn!=null)try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}//可以使用Try..with..resources语法简化conn = null;}}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。