您的位置:首页 > 编程语言 > Java开发

java,jdbc连接mysql

2016-05-01 21:51 375 查看
1.下载jdbc的驱动jar包

2.数据库模样:



3.上代码:

public class JdbcTest {
// 驱动名称
public static final String driverName = "com.mysql.jdbc.Driver";
// 连接地址
public static final String url = "jdbc:mysql://localhost:3306/libo_shopping";
// 用户名
public static final String userName = "root";
// 密码
public static final String password = "root";
// 数据库连接
public static Connection conn = null;
// sql语句执行对象
public static PreparedStatement st = null;
// 结果集对象
public static ResultSet rs = null;
/**
* 获取数据库连接的方法
*
* @return
*/
public static void getConnection() {
try {
// 1.加载驱动
Class.forName(driverName);
// 2.获取连接
conn = DriverManager.getConnection(url, userName, password);
System.out.println("成功获取连接!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 关闭连接的方法
*/
public static void close() {
try {
if(rs!=null){
rs.close();
}
if(st!=null){
st.close();
}
if(conn!=null){
conn.close();
}
System.out.println("关闭成功!!");
} catch (SQLException e) {
e.printStackTrace();
}
}

/**
* main方法
* @param args
*/
public static void main(String[] args) {
//1.获取连接
getConnection();
String sql="select * from libo_shopping.y_user";
//2.获取sql语句执行对象
try {
//通过预处理防止sql注入
st=conn.prepareStatement(sql);
//3.获取结果集对象
rs=st.executeQuery();
//4.对结果集进行处理
System.out.println("id\t登录名");
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql jdbc