如何在 javaee上 连接mysql数据库

是 jsp文件
2025-02-27 07:28:55
推荐回答(2个)
回答1:

  1. try{
        Class.forName("com.mysql.jdbc.Driver");
        }
    catch(ClassNotFoundException  e)  {}
    //定义所要用到的三个数据库应用对象
       Connection con=null; //连接对象
       Statement  sql=null; //Statement对象(SQL语句)
       ResultSet   rs=null; //结果集对象
    //进行数据源的连接
     try{
      con=DriverManager.getConnection ("jdbc:mysql://localhost/scutcs","","");//连接数据库的url  用户名和密码
      sql=con.createStatement();
      String to="Select * From user1 Where username='"+username+"'";
      rs=sql.executeQuery(to);  //根据所定义的Statement执行生成相应的结果集并存在RS中
      if(rs.next()) //判断结果集是否为空,如果不为空则表示有记录
    {
     out.print("");//如果存在返回注册页面
    }
         else {如果不存在就向数据库添加一条记录}
           }
     catch (SQLException e)  
       { out.print(e);      
       }


2.

username=root

password=

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/jsddb?useUnicode=true&characterEncoding=UTF8

maxActive=10

initialSize=1

maxWait=5000

回答2:

<%String driverName="com.mysql.jdbc.Driver";
String userName="root";
String userPwd="123456";
String dbName="students";
String url1="jdbc:mysql://localhost:3306/"+dbName;
String url2="?user="+userName+"&password="+userPwd;
String url3="&useUnicode=true&characterEncoding=UTF-8";
String url=url1+url2+url3;
Class.forName(driverName);
Connection conn=DriverManager.getConnection(url);
String sql="Insert into students_info(id,name,sex,age,weight,hight) values(?,?,?,?,?,?)";
PreparedStatement pstmt=conn.prepareStatement(sql);
request.setCharacterEncoding("UTF-8");
int id=Integer.parseInt(request.getParameter("id"));
String name=request.getParameter("name");
String sex=request.getParameter("sex");
int age=Integer.parseInt(request.getParameter("age"));
float weight=Float.parseFloat(request.getParameter("weight"));
float hight=Float.parseFloat(request.getParameter("hight"));
pstmt.setInt(1,id);
pstmt.setString(2,name);
pstmt.setString(3,sex);
pstmt.setInt(4,age);
pstmt.setFloat(5,weight);
pstmt.setFloat(6,hight);
int n=pstmt.executeUpdate();
if(n==1){%>数据插入操作成功!
<%}
else{%>数据插入操作失败!
<%}
if(pstmt!=null){pstmt.close();}
if(conn!=null){conn.close();}
%>
这是我以前在Jsp中写的往数据库保存信息的代码,你看下……