『Web』Java_Web-JDBC 增加记录操作模板
如果不能成功链接数据库,我的博客 JAVA 中有详细的介绍,可以看一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement;
public class Add {
public static void main(String[] args) throws Exception {
String driver = "com.mysql.cj.jdbc.Driver"; String userName = "root"; String userPwd = ""; String Dbname="students"; String url = "jdbc:mysql://localhost:3306/"+Dbname+"?&useSSL=false&serverTimezone=UTC"; String coding="&useUnicode=ture&characterEncoding=UTF-8"; url = url+coding;
Class.forName(driver); Connection conn = DriverManager.getConnection(url, userName, userPwd); if (!conn.isClosed()) System.out.println("Succeeded connecting to the Database!");
String sql = "insert into stu(xh,name,cj) values(2,'李四',98)"; PreparedStatement pstmt = conn.prepareStatement(sql); int n = pstmt.executeUpdate(sql);
if (n > 0) { System.out.println("添加记录成功,共添加了" + n + "条记录"); } else { System.out.println("添加不成功!"); } pstmt.close(); conn.close();
}
}
|