JDBC连接的六步实例代码(与mysql连接)
16lz
2021-12-11
JDBC的六步:
1.注册驱动
2.获取数据库的连接
3.获取数据库的操作对象
4.执行sql语句
5.处理查询结果集(如果执行的语句中没有select语句这一步不用写)
6.关闭资源
第一步:注册驱动
//异常一定是需要处理的//根据版本不同书写的代码有一些变化,老版本是DriverManager.register(new com.mysql.jdbc.Driver());//或者Class.forName("com.mysql.jdbc.Driver"); //新版本是DriverManager.register(new com.mysql.cj.jdbc.Driver());//或者Class.forName("com.mysql.cj.jdbc.Driver");
完整代码
package jdbc.com;import com.mysql.cj.protocol.Resultset; import java.sql.*;public class Test02 { public static void main(String[] args) { Connection conn = null; Statement st = null; ResultSet rt = null; try { //注册连接(可以写到一行里面) //com.mysql.cj.jdbc.Driver Driver = new com.mysql.cj.jdbc.Driver(); DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver()); //获取数据库连接 conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/liu2?serverTimezone=GMT%2B8","用户名","密码"); //获取数据库操作对象 st = conn.createStatement(); //执行sql语句 String sql = "select ename,sal from emp order by sal desc"; rt = st.executeQuery(sql); //处理查询语句 while(rt.next()){ String ename = rt.getString("ename"); String sal = rt.getString("sal"); System.out.println(ename + "," + sal); } } catch (SQLException throwables) { throwables.printStackTrace(); }finally { //关闭连接 if (rt != null) { try { rt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (st != null) { try { st.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }}
总结
更多相关文章
- 《Android和PHP最佳实践》官方站
- android EditText设置不可写
- android 使用html5作布局文件: webview跟javascript交互
- android studio调试c/c++代码
- android用户界面之按钮(Button)教程实例汇
- IM-A820L限制GSM,WCDMA上网的原理(其他泛泰机型可参考)7.13
- 锁屏界面
- android(NDK+JNI)---Eclipse+CDT+gdb调试android ndk程序
- Android(安卓)version and Linux Kernel version