初学JDBC
public class JDBCDemo1 {
public static void main(String[] args) throws Exception {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接对象
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
//3.获取执行SQL对象
Statement statement = connection.createStatement();
//4.执行SQL语句,并接收结果
int result = statement.executeUpdate("insert into user(userid,username,sex)values(1,'张三','男');");
/*//上述statement存在注入风险,执行效率也不是很高
//以下方法有效避免SQL注入的风险,先编译,后运行
String sql="insert into user(userid,username,sex)values(5,'孙七','男')";
PreparedStatement statement = connection.prepareStatement(sql);
int result =statement.executeUpdate();*/
//处理结果
if(result == 1){
System.out.println("注册成功!");
}else {
System.out.println("注册失败!");
}
//释放资源
statement.close();
connection.close();
}
}
如若插入到数据库中的汉字出现乱码,可以将上面获取连接的代码改成:
Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8”, “root”, “123456”);
说明:出现乱码问题并非是这代码出现问题,而是你在安装数据库时选用的是mysql提供的默认字符latin1,使用改字符集的情况下,即使你创建数据库时选用的字符集是utf-8,使用JDBC插入有关中文的数据依旧会出现乱码,自己可以点开自己的mysql安装目录中去查看my.ini配置文件:盘符:\Program Files\MySQL\MySQL Server 5.1
提示
以上只是我自己的看法,如有雷同纯属意外。如有错误,也请谅解,勿喷!如有收获或疑问,欢迎点赞评论!