Mysql javaBean

本文提供了一个使用JavaBean连接MySQL数据库的示例代码,包括建立连接、执行查询及显示结果的方法。此外还展示了如何通过JSP页面进行数据展示及提交表单数据到数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mysql bean


package conn;
import java.sql.*;
public class mysqlconn
{
public mysqlconn(){

}

private Connection conn = null;
private ResultSet result = null;
private String server = "127.0.0.1";
private String port = "3306";
private String driver="org.gjt.mm.mysql.Driver";
private String user ="root";
private String pass ="lingting";
private String dbname = "test";
private String URL="jdbc:mysql://"+server+":"+port+"/"+dbname+"?useUnicode=true&characterEncoding=UTF-8&user="+user+"&password="+pass;

public Connection getConn(){
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(URL);
}
catch (Exception e)
{
e.printStackTrace();
}
return conn;
}

public ResultSet executeSQL(String str){
try
{
Statement sttm=conn.createStatement();
result = sttm.executeQuery(str);
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
}




jsp code


<%@ page contentType="text/html;charset=UTF-8" import="java.sql.*"%>
<jsp:useBean id="Border" scope="page" class="Border.mysqlconn"/>

<%
ResultSet rs = null;
Connection conn = null;
conn = Border.getConn() ;
rs = Border.executeSQL("select * from cheng");
%>

<body>


My first Jsp JavaBean Mysql


<table border="1" align="center">
<tr>
<th>
id
</th>
<th>
title
</th>
<th>
price
</th>
</tr>

<%
while(rs.next()) {
String str_name=new String(rs.getString("name").getBytes("ISO-8859-1"),"UTF-8");
String str_msg=new String(rs.getString("msg").getBytes("ISO-8859-1"),"UTF-8");
%>
<tr>
<th>
<%=rs.getString("id")%>
</th>
<th>
<%= str_name%>
</th>
<th>
<%= str_msg%>
</th>
</tr>
<%}%>
<%
rs.close();
conn.close();
%>
</table>

<form name="form1" method="post" action="update.jsp">
<table width="210" border="1" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="77">title:</td>
<td width="127">
<input name="Title" type="text" id="Title">
</td>
</tr>
<tr>
<td>price:</td>
<td>
<input name="Price" type="text" id="Price">
</td>
</tr>
<tr>
<td>


<input type="submit" name="Submit" value="提交">

</td>
<td>
<input type="reset" name="Submit2" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>





update jsp

<%@ page contentType="text/html;charset=GBK" import="java.sql.*"%>
<% request.setCharacterEncoding("GBK"); %>
<jsp:useBean id="Border" scope="page" class="conn.mysqlconn" />


<%

Connection conn = null;
conn = Border.getConn() ;

String tit=request.getParameter("Title");
String prc=request.getParameter("Price");


Statement stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO cheng (name,msg) VALUES ('"+tit+"','"+prc+"')");

response.sendRedirect("index.jsp");
%>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值