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 { } }