package helloworld;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Random;
public class conn {
private static final String USERNAME = "root";
private static final String PASSWORD = "Jambone1";
private static Statement stmt;
private static Connection con;
private static final String CONN_STRING = "jdbc:mysql://localhost:3307/students?autoReconnect=true&useSSL=false";
public static void main(String[] args) throws SQLException {
String[] name1 = {"HARRY" ,"JACK" ,"THOMAS", "ALFIE ","RILEY",
"JAMES", "JOSHUA", "ETHAN", "SAMUEL", "DANIEL",
};
Random ran = new Random();
try {
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("done");
con.setAutoCommit(false);
stmt = (Statement) con.createStatement();
String name;
int salary = 100;
int batchSize = 10;
for (int i = 1; i <= batchSize; i++) {
String insert = "INSERT INTO e(nr,name,salary) VALUES('" + i +
"','" + name1 + "','" + salary + "')";
stmt.addBatch(insert);
}
int[] results = stmt.executeBatch();
System.out.println((results));
con.commit();
} catch (SQLException e) {
System.err.println("did not work--> " + e);
} finally {
con.close();
stmt.close();
}
}
}
如何使用此代码使代码将名称保存在数据库中。我发送到数据库,但不发送名称。这段代码将添加到数据库中,但是我希望名称随机化,并且它显示的不是保存为数字而是保存为数据库中的名称。
答案 0 :(得分:0)
我建议使用preparedStatement
private PreparedStatement preparedStatement;
con = DriverManager.getConnection(url, user, password);
String stmt = "INSERT INTO e (nr, name, salary,) VALUES (?, ?, ?)";
for( i = 0 ; i < batchSize; i++ ) {
preparedStatement = con.prepareStatement(stmt);
preparedStatement.setInt(1, i);
preparedStatement.setString(2, name1[i]);
preparedStatement.setDouble(3, salary);
preparedStatement.executeUpdate();
}