jdbc 功能 是作为java和数据库的桥梁
类和接口:
DriverManager 管理jdbc驱动
Conncection 连接
Statement(PrepareStatement) 增删改查
preparedstatement :是statement的子接口,通过preparestatement(sql)方法获得对象 同时预编译,执行就不用了
多了setxx方法替换占位符
区别:后者写法更加简单,sql编译一次就可以了,而且安全 防止sql注入(sql语句和用户名混为一体)
Resultset 返回结果
CallableStatement 调用数据库中的存储过程
connection.prepareCall(存储函数或者存储过程)
存储过程:无return 用out代替
存储函数 有返回值
数据库为mysql,导入jar包后
增删改查
public class jdbc {
private static final String URL="jdbc:mysql://localhost:3306/tour";
private static final String username="root";
private static final String password="1111";
//增删改
public static void update() {
Connection connection=null;
Statement stmt=null;
try{
//驱动类
Class.forName("com.mysql.jdbc.Driver");
connection= DriverManager.getConnection(URL,username,password);
stmt=connection.createStatement();
String sql="insert into ";
int count =stmt.executeUpdate(sql);
if(count>0){
System.out.println("操作成功!");}}
catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}catch(Exception e)
{e.printStackTrace();}
finally{
try{if(stmt!=null)stmt.close();
if(stmt!=null)
connection.close();
}catch(Exception e){
e.printStackTrace();}}
}
//查
public static void query() {
Connection connection=null;
Statement stmt=null;
ResultSet rs=null;
try{
//驱动类
Class.forName("com.mysql.jdbc.Driver");
connection= DriverManager.getConnection(URL,username,password);
stmt=connection.createStatement();
String sql="select name password from user ";
rs =stmt.executeQuery(sql);
while(rs.next())
{String username=rs.getString("username");
String password=rs.getString("password");
System.out.println(username+" "+password);
}
}
catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}catch(Exception e)
{e.printStackTrace();}
finally{
try{
if(rs!=null)rs.close();
if(stmt!=null)stmt.close();
if(stmt!=null)
connection.close();
}catch(Exception e){
e.printStackTrace();
}}
}
}
preparedstatement中增删改核心
String sql="insert into user value(?,?) ";
pstmt=connection.prepareStatement(sql);
pstmt.setString(1, zs);
pstmt.setInt(2, 2589);
查询
String sql="select username password from user where username like ? ";
pstmt=connection.prepareStatement(sql);
pstmt.setString(1, "%s%");
rs =pstmt.executeQuery();
while(rs.next())
{String username=rs.getString("username");
String password=rs.getString("password");
System.out.println(username+" "+password);
}
通过jsp访问数据库
也是先导包导入lib里
起一个java文件命名为xxxdao
本该是request.getParameter(" 属性")获取从网页中得到的值,设置成方法的属性
比如登录功能 就是校验输入的和数据库中已有的是否一致 那就是查询 sql= select count(*)from login where username='"+name+"' password='"+password+"'
显示登陆成功的页面 搞一个<%%>里面用request.getParameter获取用户名和密码,new一个xxxdao的对象 调用里面的那个方法
这样各司其职 java里面用以比较的用户名和密码靠参数传 jsp文件就用request内置对象完成获取
等等 对象调用dao里面的那个登录方法的时候。。是int型?
原文地址:https://blog.csdn.net/weixin_39102319/article/details/88543812
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。