java中mysql实现JDBC连接
一.在mysql控制台创建一个名为demojdbc的数据库
public class TestJDBC {
static Connection conn = null;
public static Connection getConnectionByJDBC(){
try {
//1.加载mysql的数据驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
// TODO: handle exception
System.out.println("装载驱动包出现异常!");
e.printStackTrace();
}
try {
//2.建立jdbc连接,通过drivermanager类创建数据库连接对象Connection
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcdemo", "root","");//URL=协议名+IP地址(域名)+端口+数据库名称;用户名和密码
} catch (Exception e) {
// TODO: handle exception
System.out.println("链接数据库发生异常!");
e.printStackTrace();
}
return conn;
}
public static void test(){
String sql ="select * from user";
getConnectionByJDBC();
try {
//3.创建statement对象,用来执行静态的SQL语句并返回它所生成的结果对像
Statement stmt = conn.createStatement();
//4.执行SQL语句,也可用通过execuUpdate()方法进行插入和删除等操作
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println("用户名:"+username+" 密码是:"+password);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
}finally{
//5.用.close()关闭数据库连接,关闭连接时避免异常发生时在try语句块关闭没有执行
try {
if (conn != null)
conn.close();
} catch (Exception e2) {
// TODO: handle exception
System.out.println(e2.getMessage());
e2.printStackTrace();
}
}
}
public static void main(String[] args){
TestJDBC testjdbc = new TestJDBC();
testjdbc.test();
}
}

浙公网安备 33010602011771号