java连接navicat
时间: 2024-03-21 12:36:20 浏览: 51
Java连接Navicat是一种常见的数据库连接方式,可以通过Java代码与Navicat进行交互。下面是一个简单的示例代码,演示了如何使用Java连接Navicat数据库:
```java
import java.sql.*;
public class NavicatConnectionExample {
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "123456";
// 声明连接对象
Connection conn = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
conn = DriverManager.getConnection(url, username, password);
// 执行SQL语句
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM mytable";
ResultSet rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("id: " + id + ", name: " + name);
}
// 关闭结果集和连接
rs.close();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
上述代码中,我们首先加载了MySQL数据库的驱动程序,然后使用`DriverManager.getConnection()`方法建立与Navicat数据库的连接。接着,我们创建了一个`Statement`对象,执行了一条查询语句,并通过`ResultSet`对象获取查询结果。最后,我们关闭了结果集和连接。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![png](https://img-home.csdnimg.cn/images/20210720083516.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)