gpt4 book ai didi

java - 在mysql数据库中使用servlet插入数据

转载 作者:行者123 更新时间:2023-11-29 00:21:39 27 4
gpt4 key购买 nike

import java.sql.*;
import java.util.*;

public class app1conn {
String url="jdbc:mysql://localhost:3306/test",uname,password;
Connection con;
PreparedStatement ps;

app1conn() throws SQLException{

DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con= DriverManager.getConnection(url,"root","");

}

public void insert (String name,String email,String age,String dob)throws Exception{


ps=con.prepareStatement(url);
//ps=new con.PreparedStatement ("insert into info(name,email,age,dob) values(?,?,?,?)") ;
ps.setString(1,name);
ps.setString(2,email);
ps.setString(3,age);
ps.setString(4,dob);
ps.executeUpdate();

}
public Vector getData() throws SQLException{
ps=con.prepareStatement("Select * from info");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rms=rs.getMetaData();
Vector data=new Vector();

while(rs.next()){

Vector temp=new Vector();
temp.add(rs.getString(1));
temp.add(rs.getString(2));
temp.add(rs.getString(3));
temp.add(rs.getString(4));
temp.add(rs.getString(5));


data.add(temp);

}
return data;
}

public Vector getDataById(String id) throws SQLException{
ps=con.prepareStatement("Select * from info where id=?");
ps.setInt(1,Integer.parseInt(id));
ResultSet rs=ps.executeQuery();
ResultSetMetaData rms=rs.getMetaData();
Vector data=new Vector();

while(rs.next()){

Vector temp=new Vector();
temp.add(rs.getString(1));
temp.add(rs.getString(2));
temp.add(rs.getString(3));
temp.add(rs.getString(4));
temp.add(rs.getString(5));


data.add(temp);

}
return data;
}
void update_info(String name,String email,String age,String dob,String id) throws SQLException{
ps=con.prepareStatement ("update info set name=?,email=?,age=?,dob=? where id=?");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, age);
ps.setString(4, dob);


ps.executeUpdate();
}

}

我正在尝试插入数据..当我点击提交按钮时..

它显示 null 作为输出..

最佳答案

String insertSQL = "insert into info(name,email,age,dob) values(?,?,?,?)";
PreparedStatement ps = dbConnection.prepareStatement(insertSQL);
ps.setString(1,name);
ps.setString(2,email);
ps.setString(3,age);
ps.setString(4,dob);
ps.executeUpdate();

或者

String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "abc");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();

引用this article

关于java - 在mysql数据库中使用servlet插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20812711/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com