
import java.sql.*
/**
* @author xys
*/
public class ConnectMysql {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306/databaseName"
String user = "mysqluser"
String password = "password"
String driverClass = "com.mysql.cj.jdbc.Driver"
Connection connection = null
Class.forName(driverClass)
try {
connection = DriverManager.getConnection(url, user, password)
} catch (SQLException e) {
e.printStackTrace()
}
if (connection != null) {
System.out.println("数据库连接成功")
} else {
System.out.println("数据库连接失败")
connection.close()
}
return connection
}
public void getResult() throws ClassNotFoundException, SQLException {
// 实例化 Statement 对象
Statement statement = getConnection().createStatement()
// 要执行的 Mysql 数据库 *** 作语句(增、删、改、查)
String sql = ""
// 展开结果集数据库
ResultSet resultSet = statement.executeQuery(sql)
while (resultSet.next()) {
// 通过字段检索
int id = resultSet.getInt("id")
String name = resultSet.getString("name")
// 输出数据
System.out.println("ID : " +id)
System.out.println("name :" + name)
}
// 完成后需要依次关闭
resultSet.close()
statement.close()
getConnection().close()
}
}
使用java连接MySQL数据库与其他的数据库连接核心是一样的,如果说区别,那就是所需的驱动不一样。
工具/原料
MySQL、JDK
方法/步骤
1、首先需要安装好JDK(配置环境变量),如图所示:
2、其次要安装好MySQL数据库,可以使用可视化Navicar For MySQL,如图所示:
3、最后通过代码进行连接。
(1)确定连接路径URL:
String url="jdbc:mysql://localhost(可以是本机IP地址):3306(端口号)/mysqltest(数据库名称)?"+"user=用户账号&password=用户密码&useUnicode=字符编码"
(2)加载驱动:
Class.forName("com.mysql.jdbc.Driver")
(3)连接,获取Connection对象
Connection conn=DriverManager.getConnection(url)
(4)可以通过conn对象检验连接与否。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)