那么我有一个学校项目,我不得不使用MySQL(这是一个问答游戏)。我创建了一个SQLHandler类,它非常通用,您可以在每个项目中使用它,其中包括jdbc mysql连接器,可以从here下载。我下载了平台独立版本,这是一个jar文件。随意使用下面的代码:
import java.sql.*;
public class SQLHandler {
private String host;
private String port;
private String db;
private String user;
private String pw;
public SQLHandler(String host,String port, String db, String user,String pw){
this.host=host;
this.port=port;
this.db=db;
this.user=user;
this.pw=pw;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public String getHost(){
return host;
}
public String getPort(){
return port;
}
public String getDb(){
return db;
}
public String getPw(){
return pw;
}
public String getUser(){
return user;
}
public String URLConfig(String host, String port, String dbaseName){
String url="jdbc:mysql://"+host+":"+port+"/"+dbaseName;
return url;
}
public void inputQuery(String command) throws SQLException{
String url=URLConfig(getHost(),getPort(),getDb());
Connection conn=DriverManager.getConnection(url,getUser(),getPw());
PreparedStatement query=conn.prepareStatement(command);
query.executeUpdate(command);
}
public String outputQuery(String command,int cnum)throws SQLException{ //cnum defines the number of columns in your table
String url=URLConfig(getHost(),getPort(),getDb());
Connection conn=DriverManager.getConnection(url,getUser(),getPw());
PreparedStatement query=conn.prepareStatement(parancs);
ResultSet result=query.executeQuery(parancs);
String res="";
while(result.next()){
for(int i=1; i<=cnum; i++){
res=res+result.getString(i)+" ";
}
}
return res;
}
}
我希望它会帮助你的!
此代码会让我的大脑受伤。 – AWT