欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

java实现MySql连接七步

程序员文章站 2022-05-29 08:58:19
...

package org.cjit.io.student; /** * java实现MySQl的JDBC连接的七步 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcTest { * @p

package org.cjit.io.student;
/**
* java实现MySQl的JDBC连接的七步
*/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcTest {



* @param args
*/
private static Connection con;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//1.载入JDBC驱动程序包
Class.forName("com.mysql.jdbc.Driver");
//2.定义连接URL
String url = "jdbc:mysql://localhost:3306/test?user=root&password=root";
//3.建立连接
con = DriverManager.getConnection(url);
//4.创建Statement对象
Statement stmt = con.createStatement();
//5.执行查询操作
String query = "select*from person";
ResultSet rs = stmt.executeQuery(query);
//6.对查询结果进行处理
while (rs.next()) {
String name=rs.getString("姓名");
String password=rs.getString("密码");
System.out.println(rs.getString(2));
System.out.println(name+":"+password);

}

} catch (ClassNotFoundException e) {// 由16行抛出
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {// 由con,stmt抛出
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//7.关闭连接
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.exit(0);
}

}
}

}

}