用JDBC操作数据库的时候,如果需要往表中插入一些常量,则sql语句拼接起来十分的费劲,因此我们可以使用PreparedStatement来解决这个问题。
直接上代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MySqlTest {
public static void main(String[] args){
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名-mydata
String url = "jdbc:mysql://192.168.3.103:3306/mydata";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "123456";
//要执行的mysql语句
String sql = "INSERT into tb_dept VALUES(?,?,?)";
Connection conn = null;
PreparedStatement pstmt = null;
try{
// 加载驱动程序
Class.forName(driver);
// 连续数据库
conn = DriverManager.getConnection(url, user, password);
// pstmt用来执行SQL语句
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 5); //sql中的第一个参数
pstmt.setString(2, "win"); //sql中的第二个参数
pstmt.setString(3, "win7"); //sql中的第三个参数
pstmt.executeUpdate();
} catch (ClassNotFoundException e){
e.printStackTrace();
} catch (SQLException e){
e.printStackTrace();
} finally {
//将打开的资源都关闭掉
try {
if(res != null){
res.close();
res = null;
}
if(pstmt != null){
pstmt.close();
pstmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
当然,也可以查询中使用:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MySqlTest {
public static void main(String[] args){
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名-mydata
String url = "jdbc:mysql://192.168.3.103:3306/mydata";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "123456";
//要执行的mysql语句
String sql = "select * from tb_dept where dept_name=?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet res = null;
try{
// 加载驱动程序
Class.forName(driver);
// 连续数据库
conn = DriverManager.getConnection(url, user, password);
// pstmt用来执行SQL语句
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "mac"); //sql中的第一个参数
res = pstmt.executeQuery();
while(res.next()){
System.out.println(res.getString("dept_name"));
}
} catch (ClassNotFoundException e){
e.printStackTrace();
} catch (SQLException e){
e.printStackTrace();
} finally {
//将打开的资源都关闭掉
try {
if(res != null){
res.close();
res = null;
}
if(pstmt != null){
pstmt.close();
pstmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}