Java通过jdbc连接Mysql数据库

import java.sql.Connection;

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

import cn.itcast.domain.User;

public class Demo2 {

public static void main(String[] args){

String url ="jdbc:mysql://localhost:3306/day14";
String username="root";
String password="root";

Connection conn = null;
Statement st = null;
ResultSet rs = null;

try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取与数据库的连接
conn = DriverManager.getConnection(url, username, password);

//3.获取用于向数据库发送sql的statement
st = conn.createStatement();

//4.向数据发送sql
String sql = "select * from users";
rs = st.executeQuery(sql);

//5.取出结果集的数据
while(rs.next()){
System.out.println("id= "+rs.getObject("id"));
System.out.println("name= "+rs.getObject("name"));
System.out.println("password= "+rs.getObject("password"));
System.out.println("email= "+rs.getObject("email"));
System.out.println("birthday= "+rs.getObject("birthday"));
}
} catch (Exception e) {
e.printStackTrace();
}
finally
{    
//6.关闭连接
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}    
}

}
}
原文地址:https://www.cnblogs.com/wangyi666/p/9493375.html