1、配置好环境,主要是安装mysql和下载连接需要的包(我用的是mysql-connector-java-5.1.3-rc-bin.jar)
2、注册驱动 Class.forName("com.jdbc.mysql.Driver");
3、创建连接 Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/test",user,password);
4、创建表达式 Statement stmt = con.createStatement();
5、执行sql语句并获得相应的结果集 ResultSet rs = stmt.executeQuery("select * from tables");
6、获取结果while(rs.next()){System.out.println(rs.getString(1));}
7、关闭连接rs.close();stmt.close();con.close();
public class Jdbc01 { public static void main(String[] args) throws Exception { Driver d = new Driver(); DriverManager.registerDriver(d); //Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","123456"); //本机 ,端口是默认的,数据库。用户名,密码。 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select *from student"); //执行查询语句 while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String sex = rs.getString("sex"); String address = rs.getString("address"); System.out.println(id+" "+name+" "+age +" "+ sex+" " + address); } rs.close(); stmt.close(); conn.close(); } }
时间: 2024-11-03 06:31:35