Java WEB编程tomcat验证连接数据库mysql测试:
1、将mysql的jdbc驱动程序放到tomcat的lib中:mysql_connect_jdbcdriver.jar
test1.jsp中内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%><%@ page import="java.sql.*" %>
<html>
<head>
<title>My JSP starting page</title>
</head>
<body>
<h1>
<%
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver")
//建立连接
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","mysql")
//创建状态
Statement state=con.createStatement()
//插入
String sql="insert into student values('Gosling','java'),('002','zxy')"
state.executeUpdate(sql)
//更新
String sql1="update student set stuID='001' where stuName='java'"
state.executeUpdate(sql1)
//修改
String sql3="update student set stuName='html' where stuID='002'"
state.executeUpdate(sql3)
//查询
String sql2="select stuID,stuName from student where stuID='001'"
String sql2="select * from student"
ResultSet rs=state.executeQuery(sql2)
while(rs.next()){
String uID=rs.getString("StuID")
String uName=rs.getString("stuName")
out.println("stuID:"+uID+" "+"stuName:"+uName+"<br>")
}
out.println("Operator success..."+"<br>")
state.close()
con.close()
} catch (Exception e) {
e.printStackTrace()
}
%>
</h1>
</body>
</html>
2、连接mysql数据库,做如下 *** 作:
mysql> create database mydbQuery OK, 1 row affected (0.02 sec)
mysql> use mydb
Database changed
mysql> create table student(stuID char(20),stuNamechar(20))
Query OK, 0 rows affected (0.08 sec)
mysql>insert into student values('abc','jack')
Query OK, 1 row affected (0.03 sec)
3、然后运行test1.jsp, 显示如下(success)即为成功。
tomcat怎么连接mysql传统方法:1、本人使用JDBC驱动mysql-connector-java-5.1.6-bin.jar,将此驱动包放到%Tomcat_Home%\common\lib\下,
2、在应用程序中加载此包,右键项目属性->java build path->libraries->external libraries
3、在应用程序中加载驱动,Class.forName("com.mysql.jdbc.Driver").newInstance()
4、 用java.sql.DriverManager类取得一连conn=DriverManager.getConnection(url)
5、用java.sql.Statement接口创建stmt 对象,stmt=conn.createStatement()
或java.sql.PreraredStatement接口 pstmt
6、 用java.sql.ResultSet接口创建rst对象,rst = stmt.executeQuery(sql语句)
7、 处理结果集,断开数据库连接。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)