一、配置好环境:
需要安装配置的软件环境:
jdk、tomcat服务器、eclipse、mysql(可以使用附加的图形界面软件工具:navicat for mysql)、webstorm。
二、编写web项目文件
先用webstorm编辑好web项目文件。
三、根据web项目的数据需求设计和建造数据库表。
用例:
新建数据库名为:users;
新建表 名为:user。有两个字段,分别为 id、username。
如图:
——————————————————————————————————————————————————————————————————————————
四、用eclipse链接数据库并调用数据库的数据。
1、导入或新建web项目:
例,新建一个web项目并连接与调用数据库的数据:
打开eclipse:File>new>other>web文件夹下>Dynamic Web Project(选中)>next>Project name:命名为想要的项目名>Finish
新建话——如图:
2、在web6项目文件夹下,点击java Resourses>src,选中文件夹src,右键new一个package:
将包命名为testConnection(自己定义的名字)
在testConnection包下新建class:
2、配置eclipse的build path>、Server>Runtime Environments
1将工具包mysql-connector-java-5.1.38-bin.jar(工具包的下载地址)复制在eclipse中:
复制工具包在web5(项目)>WebContent>WEB-INF>lib目录下面:
2配置eclipse的build path>:
点击Window>preferences>在新跳出来的窗口中的左侧列表中找到Server点击展开>选择Runtime Environments>add
在跳出来的窗口中点击选择Apache选择你电脑相对应的tomcat服务器版本,再点击finish>ok:
3配置Server>Runtime Environments
在新出现的窗口中选择 Add Library:
选择Server Runtime>Nest>
点击选中服务器>finish>ok
新建并编写TestConnection.java文件为以下内容:
package TestConnection; //包名
import java.sql.Connection; //导入所需要的包
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestConnection {
public static Connection getConnection() {
Connection conn = null;
String ip = "jdbc:mysql://localhost:3306/users?useSSL=false"; //"users"是我们的建的数据库名。
String username = "root"; //"数据库的root用户"
String password = "123456"; //数据库的密码
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(ip, username, password);
} catch (ClassNotFoundException e) {
//什么错误处理都没做
e.printStackTrace();
} catch (SQLException e) {
// 什么错误处理都没做
e.printStackTrace();
}
return conn;
}
public static void getUser(Connection conn){
Statement stmt=null;
ResultSet rs=null;
try {
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from users1introfile where id=1"); //调用数据库数据,使“rs"能引用调用筛选处理出来的表格数据
if(rs.next()){
int id=rs.getInt("id"); //将数据库里调用出来的id的值 赋值给变量”id”;
String username=rs.getString("username"); //将数据库里表users1introfile里调用出来的username的值 赋值给变量”username”;
System.out.println(username); //输出id和username的值;
System.out.println(id);
}
} catch (SQLException e) {
// 什么错误处理都没做
e.printStackTrace();
}finally{
try{
rs.close(); //关闭连接
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Connection conn = TestConnection.getConnection(); //使变量”conn“能 引用 已链接到的数据库的对象
TestConnection.getUser(conn); //调用getUser(Connection conn)方法
//检测是否连接到数据库的测试代码
if (conn != null) {
System.out.println("I have connection");
} else {
System.out.println("no connection");
}
try {
conn.close(); //关闭连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
************************************************************************************************************************
————————————————————————————————————————————
测试:
如图显示:表明已经成连接上数据库