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

eclipse连接MySQL数据库

2017-11-22 19:16 204 查看
首先导入JDBC包

mysql-jdbc-CSDN下载点击打开链接

Eclipse工程连接Mysql说明_百度经验 https:// href="http://jingyan.baidu.com/article/fb48e8be386b7c6e622e1488.html" target=_blank>jingyan.baidu.com/article/fb48e8be386b7c6e622e1488.html

然后就是在eclipse中建一个项目,编写语句如下:

String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/sc";//3306是我的mysql占用端口号,sc是我提前建好的数据库
String user = "root";//mysql用户名
String password = "root";;//mysql密码

Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

try{//注:此次一定要加异常处理,因为diver不一定能正确找到
//1.注册驱动
Class.forName(driver);
//2.获取链接
conn = DriverManager.getConnection(url,user,password);
//3.预处理sql
String sql = "select * from tbl_student";
pstmt = conn.prepareStatement(sql);
//4.执行sql操作(更新操作,查询操作),如果有结果集处理集合
rs = pstmt.executeQuery();
while(rs.next()){
long id = rs.getLong("id");
String name = rs.getString("name");
System.out.println(id+","+name);
}
}catch(Exception e){
e.printStackTrace();
}finally{
//5.释放资源
if(rs != null){
rs.close();
}
if(pstmt != null){
pstmt.close();
}
if(conn != null){
conn.close();
}
}


另一种sql语句,更新,删除,修改操作,无结果集合:

//4.执行sql
String sql = "insert into tbl_student(name,birth) values(?,?)";//占位符
PreparedStatement pstmt = conn.prepareStatement(sql);
//5.替换占位符
pstmt.setString(1, "terry");
pstmt.setString(2,"女");
int num = pstmt.executeUpdate();
System.out.println("保存了"+num+"条信息");
//更新操作,对所有数据有影响操作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息