怎样用java连接mysql,并且输出mysql数据库test表中的一列值,谢谢
发布网友
发布时间:2022-04-10 14:30
我来回答
共1个回答
热心网友
时间:2022-04-10 15:59
要使用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;
}
}