JDBC练习----增加数据
例:向Demo02数据库中增加一条数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JBDCDemo02 {
public static void main(String[] args){
Statement stmt = null;
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///demo01", "root", "root");
String sql = "insert into demo02 values(3, 'Cook', 10, 'Cook@example.com')";
stmt = conn.createStatement();
int count = stmt.executeUpdate(sql);
System.out.println(count);
if (count>0){
System.out.println("添加成功。");
}else {
System.out.println("SQL语句有问题吧。");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
if (stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
}