我正在编写连接MySQL数据库的java代码。我有一个连接,但我无法将数据显示在我的JFrame中的标签中。所以我已连接到我的XAMPP数据库中的数据库软件,但我无法将数据显示在标签中
ResultSet rs;
ResultSetMetaData rsmd = null;
int colCount = 0;
String[] colNames = null;
try {
rs = engine.executeQuery("select * from music");
rsmd = rs.getMetaData();
colCount = rsmd.getColumnCount();
colNames = new String[colCount];
for (int i = 1; i <= colCount; i++) {
colNames[i - 1] = rsmd.getColumnName(i);
}
String[] currentRow = new String[colCount];// array to hold the
// row data
while (rs.next()) { // move the rs pointer on to the next record
// (starts before the 1st)
for (int i = 1; i <= colCount; i++) {
currentRow[i - 1] = rs.getString(i);
}
}
//System.out.println(authenticated);
}
catch (SQLException a)
{
System.err.println("SQLException: " + a.getMessage());
}
答案 0 :(得分:0)
将此代码用于其工作
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.ResultSetMetaData;
public class Db {
public static void main(String arg[]) throws SQLException,
ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/dbname", "root", "");
java.sql.Statement stmt = conn.createStatement();
String query = "select * from music";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columncount = rsmd.getColumnCount();
for(int i = 1 ; i < columncount ; i ++)
System.out.print(rsmd.getColumnName(i));
System.out.println();
while (rs.next()) {
for(int i = 1 ; i < columncount ; i ++)
{
System.out.print(rs.getString(i));
}
System.out.println();
}
conn.close();
}
}
答案 1 :(得分:0)
由于您希望为数据库连接提供单独的类,并在其他地方使用此连接,您可以执行以下操作。
public class SQLConnect {
public static Connection ConnectDb() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/databasename", "root", "");
} catch (SQLException ex) {
Logger.getLogger(SQLConnect.class.getName()).log(Level.SEVERE, null, ex);
}
return conn;
}
catch (ClassNotFoundException e) {
System.out.println("not connected");
e.printStackTrace();//print extra info if error is thrown
return null;
}
}
}
使用此课程如下
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
try {
conn = SQLConnect.ConnectDb();
String sql = "SELECT * FROM somedatabase WHERE somevalue = ? ";
pst = conn.prepareStatement(sql);
pst.setString(1, CriminalID);
rs = pst.executeQuery();
if(rs.next()) {
/*
* set values of labels to those from database
*/
jLabel.setText(rs.getString("Column name"));
}
这将从数据库获取数据,其中某些值等于您指定的任何值