JDBC:Java Data Base Connectivity java数据库连接
1.组成JDBC的两个包:主要是接口
java.sql javax.sql
2.相应JDBC的数据库实现
在tomcat的目录下面添加mysql-connector-java-5.0.8-bin.jar这个数据库驱动包
package com.tsh.web; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** */ public class DbServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** */ public DbServlet() { super(); // TODO Auto-generated constructor stub } /** */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 注册数据库驱动 //DriverManager.registerDriver(new Driver()); //使用反射的方式 Class.forName("com.mysql.jdbc.Driver"); //获取数据库连接,导包的时候,注意要导java.sql下的,面向接口编程 Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/java","root","root"); //获取传输器对象 Statement statement=conn.createStatement(); //获取结果集对象 ResultSet resultSet=statement.executeQuery("select * from user"); //遍历 while(resultSet.next()){ String username=resultSet.getString("username"); response.getWriter().write(username); } } catch (Exception e) { e.printStackTrace(); } } /** */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }