怎样用java连接mysql,并且输出mysql数据库test表中的一列值,谢谢

2024-12-25 13:43:07
推荐回答(1个)
回答1:

要使用mysql的jar包,数据库名为test,表名shop,列名shopName
package com.yunix;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test {

public static void main(String []args){
Connection con = getAccessCon();
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from shop");
while(rs.next()){
System.out.println(rs.getString("shopName"));
}
rs.close();
st.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

public static Connection getAccessCon(){
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=root");
}catch(Exception e){
e.printStackTrace();
}
return con;
}
}