java 使用 druid 修改sql
时间: 2024-04-29 08:22:36 浏览: 9
Java可以使用Druid来连接数据库,并使用Druid API修改SQL语句。Druid是一个高性能、可靠的开源数据库连接池,它支持JDBC和ODBC,可以为Java应用程序提供高效的数据访问。
下面是一个简单的使用Druid修改SQL语句的示例代码:
```java
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws SQLException {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("password");
DruidPooledConnection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement("update users set name = ? where id = ?");
statement.setString(1, "newName");
statement.setLong(2, 123);
int updateCount = statement.executeUpdate();
System.out.println("Updated " + updateCount + " rows.");
statement.close();
connection.close();
}
}
```
这个示例代码连接到本地MySQL数据库,修改了一个名为“users”的表中ID为123的行的“name”列的值。首先,创建了一个Druid数据源,并设置了数据库连接的URL、用户名和密码。然后,从数据源中获取一个连接,并准备执行SQL语句。使用`PreparedStatement`类设置要修改的值和条件,并使用`executeUpdate()`方法执行SQL语句。最后,关闭语句和连接。
需要注意的是,这个示例代码没有使用Druid的一些高级功能,如连接池的管理和监控等。在实际开发中,应该根据实际情况配置和使用Druid,以提高数据库访问的性能和可靠性。