import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; public class Test { public static void main(String[] args) throws SQLException, ClassNotFoundException { System.out.println(lianJie()); query("select * from dbtest1.tb1"); } public static Connection lianJie() throws ClassNotFoundException, SQLException { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("数据库驱动加载成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql?characterEncoding=UTF-8", "root", "123456"); System.out.println("数据库连接成功"); } catch (SQLException e) { e.printStackTrace(); } return con; } //调用它的方法如下: public static void query(String query) throws SQLException, ClassNotFoundException { //获取connection对象 Connection connection = lianJie(); //3.准备SQL语句 PreparedStatement pStatement = connection.prepareStatement(query); //4.执行SQL语句 ResultSet resultSet = pStatement.executeQuery(); System.out.println(resultSet.wasNull()); //6.关闭连接 resultSet.close(); pStatement.close(); connection.close(); } }
mysql使用jdbc连数据库纯代码记录
最新推荐文章于 2022-08-28 18:19:39 发布