怎样用java连接mysql,并且输出mysql数据库test表中的一列值,谢谢
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;
}
}
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;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询