jdbc连接数据库

jdbc连接数据库测试:

 1 import java.sql.*;
 2 
 3 public class jdbcTest {
 4     public static void main(String[] args) throws ClassNotFoundException, SQLException {
 5         //1、加载驱动
 6         Class.forName("com.mysql.jdbc.Driver");
 7         //2、用户信息和url
 8         String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true";
 9         String username = "root";
10         String password = "123456";
11         //3、连接成功,数据库对象
12         Connection connection = DriverManager.getConnection(url, username, password);
13 
14         //4、执行sql的对象
15         Statement statement = connection.createStatement();
16         //5、执行sql的对象去执行sql,可能存在结果,查看返回结果
17         String sql = "select * from person";
18         ResultSet resultSet = statement.executeQuery(sql);
19         while (resultSet.next()){
20             System.out.print("id=" + resultSet.getObject("id"));
21             System.out.print("\tname=" + resultSet.getObject("name"));
22             System.out.println("\tage=" + resultSet.getObject("age"));
23         }
24         //6、释放连接
25         resultSet.close();
26         statement.close();
27         connection.close();
28     }
29 }

 

posted @ 2021-08-31 21:52  meteor119  阅读(37)  评论(0编辑  收藏  举报