1、软件介绍:
myeclipse:java编译器
mysql:数据库
servlet:java浏览器服务
navicat:数据库管理工具
2、步骤
(1)软件安装
(2)mysql连接navicat及建库
?
(4)在myeclipse中建立javaweb项目并完成服务器的配置
3、javaweb项目连接mysql
?(1)mysql驱动安装(官网下载:mysql5.7可以使用5.1驱动)
?
(2)mysql包引入
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Driver;
import com.mysql.jdbc.PreparedStatement;
public class demo extends HttpServlet {
//连接数据库
private final static String DBU = "jdbc:mysql://localhost:3306/demo";
private final static String DBUSER = "root";
private final static String DBUPASS= "123456";
//初始化sql类
private static java.sql.Connection coon=null;
private static java.sql.PreparedStatement pst = null;
private static ResultSet rs = null;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try{
Class.forName("com.mysql.jdbc.Driver");
coon = DriverManager.getConnection(DBU,DBUSER,DBUPASS);
System.out.println("连接成功");
//使用mysql语句
String sql = "select * from demouser";
pst = coon.prepareStatement(sql);
rs = pst.executeQuery();
String name = null;
String age = null;
//遍历数据
while(rs.next()){
name = rs.getString("name");
age = rs.getString("age");
System.out.println("name"+name+"\t"+"age"+age);
System.out.println("\n");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
rs.close();
pst.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
4、验证连接
(1)启动服务器
?
(2)控制台输出
?
|