public class MysqlConnect {
//定义MySQL数据库的连接地址
public static final String DBURL = "jdbc:mysql://ip:port/数据库名?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false";
//MySQL数据库的连接用户名和连接密码
public static final String DBUSER = "用户";
public static final String DBPASS = "密码";
public static final String SQLNAME = "com.mysql.jdbc.Driver";//驱动
public void mysqlConn(String sql) {
Connection conn = null;
int id;
String name = null;
String count = null;
try{
Class.forName(SQLNAME);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
// sql = "sql语句";
try {
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
System.out.println(conn);
Statement stmt = conn.createStatement();
ResultSet resultSet = stmt.executeQuery(sql);
while (resultSet.next()){
id = resultSet.getInt("id");//通过字段拿值
name = resultSet.getString("name");//通过字段拿值
count = resultSet.getString("count(1)");//通过字段拿值
System.out.println("id: " + id + ", name: " + name + ", count: " + count);
}
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
maven依赖包:
<!-- MySql 5.5 Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>