Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <%@ page contentType="text/html;charset=gbk"%>
- <%@ page import="java.sql.*"%>
- <%
- // 定义数据库驱动程序,"com.mysql.jdbc.Driver"不用更改,适用于所有mysql程序
- String DBDRIVER = "com.mysql.jdbc.Driver" ;
- // 定义数据库连接地址,"jdbc:mysql://localhost:3306/你的数据库名称",前面同样适用所有mysql程序,后面是你的数据库名称
- String DBURL = "jdbc:mysql://localhost:3306/feuda" ;
- // 定义数据库连接对象,属于java.sql包中的接口,所以才有<%@ page import="java.sql.*"%>这一步
- Connection conn = null ;
- // 定义Statement对象,用于操作数据库
- Statement stmt = null ;
- // 定义一字符串变量,用于保存SQL语句
- String sql = null ;
- %>
- <%
- //1.加载驱动程序
- try
- {
- Class.forName(DBDRIVER) ;
- }
- catch(Exception e)
- {
- //在实际项目里不可以通过out.println将错误直接这样打印出来,否则会存在安全性问题,这里只是出于演示目的
- out.println("数据库驱动程序加载失败!") ;
- }
- //2.连接数据库
- try
- {
- //下面root为登录SQLyog Enterprise时的用户名,admin是你配置Mysql时设置的密码
- conn = DriverManager.getConnection(DBURL,"root","admin") ;
- }
- catch(Exception e)
- {
- out.println("数据库连接失败!") ;
- }
- //3.操作数据库
- try
- {
- stmt = conn.createStatement() ;
- sql = "INSERT INTO person(name,password,age) VALUES ('Feuda','feuda',21)" ;
- //sql = "UPDATE person SET name='Zhengshuang' WHERE id = 4" ;
- //sql = "DELETE FROM person WHERE id = 5" ;
- stmt.executeUpdate(sql) ;
- }
- catch(Exception e)
- {
- out.println("操作数据库失败!") ;
- }
- //4.关闭数据库
- try
- {
- stmt.close() ;
- conn.close() ;
- }
- catch(Exception e)
- {
- out.println("关闭数据库失败! ") ;
- }
- %>
Add Comment
Please, Sign In to add comment