JAVA MySQL连接
程序员文章站
2024-01-27 12:04:46
...
第一步下载
http://dev.mysql.com/downloads/connector/j/
第二步,解压并将解压后的jar放入WEB-INF下的lib中
第三步 在idea中按住ctrl+shift+alt+s打开
第四步:测试代码
package test.wg.c01.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class test {
//JDBC驱动名以及数据库URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/wg";
//数据库的用户名与密码
static final String USER = "root";
static final String PASSWORD = "123";
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("链接数据库。。。。");
connection = DriverManager.getConnection(DB_URL,USER,PASSWORD);
//执行查询
System.out.println("实例化Statement对象。。。。");
statement = connection.createStatement();
String sql;
sql = "SELECT user_name,password from tbl_user";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
String userName = resultSet.getString("user_name");
String password = resultSet.getString("password");
System.out.println("UserName:"+userName);
System.out.println("Password:"+password);
}
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
显示成功
上一篇: java连接mysql