所谓JDBC全称Java Database Connectivity,就是Java操作数据库。
数据库的选择
在这里我使用的是MySQL。对!就是辣个结构化数据库
首先部署还环境,随意创建一个数据库、一个数据表、插入一条数据。。。。
JDBC开始操作
首先在eclipse中部署jar包,看图这里是我创建JDBC项目树,lib中对jar包右键build path…(全名忘了。。。)部署
要看操作?操作和解释都在源码里!
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;;
public class demo01 {
public static void main(String[] args) throws Exception {
//加载驱动类
Class.forName("com.mysql.jdbc.Driver");
//Connection接口
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/testJDBC","root","123456");
Statement stmt=conn.createStatement();
// System.out.println(conn);
String uname="yang";
String upwd="123";
String sql="select count(*) from user where uname='"+uname+"' and upwd='"+upwd+"'";
ResultSet rs=stmt.executeQuery(sql); //执行sql语句
int count=-1;
if(rs.next()) {
count=rs.getInt(1);
}
System.out.println(count);
}
}
web访问数据库
上一篇说到JSP就是在HTML中嵌套Java代码,那就好操作了!直接将上面源码贴进JSP中,稍作改进即可运行
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<!-- 导包 -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Class.forName("com.mysql.jdbc.Driver");
//Connection接口
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/testJDBC","root","123456");
Statement stmt=conn.createStatement();
System.out.println(conn);
String uname=request.getParameter("uname");
String upwd=request.getParameter("upwd");
String sql="select count(*) from user where uname='"+uname+"' and upwd='"+upwd+"'";
ResultSet rs=stmt.executeQuery(sql);
int count=-1;
if(rs.next()) {
count=rs.getInt(1);
}
if(count==1) {
out.println("登陆成功");
}else{
out.println("密码错误");
}
%>
</body>
</html>