jdbc随笔
通过jdbc连接数据库的基本步骤:
导入jar包驱动类
jdbc语法:jdbc:子协议:厂商内容
对于mysql而言:jdbc:mysql://主机地址:端口号/库名
例: jdbc:mysql://localhost:3306/test
jdbc获取数据库连接:
//准备四个参数
//加载数据库驱动类
//利用DriverManager的getConnection方法获取数据库连接
代码示例:
//准备四个参数 String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "123456"; String driverClass="com.mysql.jdbc.Driver"; Connection conn = null; Statement statement=null; try { Class.forName(driverClass); //获取数据库连接 conn = DriverManager.getConnection(url,username,password); //statement是具体执行SQL的对象! statement = conn.createStatement(); String sql = "update stu1 set `name` = 'dehua' where id = 1"; //该executeUpdate方法可以执行sql语句的增删改操作,而且会返回一个结果,这个结果表示受影响的行数! }
catch(Exception e){} finally{ if(statement != null){ try { statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
需要注意:如果是对表的增删改操作我们使用的是:statement.executeUpdate(sql);
浙公网安备 33010602011771号