Java连接MySQL问题,求大神帮忙
新人,在家自学java,学到JDBC数据库编程,遇到问题无法处理,求大神帮忙。问题如下
代码1如下:(在MySQL数据库中创建一个名称为db_user的数据库。使用纯java驱动方式连接数据库:)
package com.mxl.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionDB{
public static void main(String[] args){
Connection conn =null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/db_user";
conn =DriverManager.getConnection(url,"root","root");
System.out.println("连接数据库成功!");
}catch(Exception e){
System.out.println("数据连接失败!");
}finally{
try{
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
问题1:运行显示:数据连接失败!
java.lang.NullPointerException
at com.mxl.jdbc.ConnectionDB.main(ConnectionDB.java:16)
代码2:
package com.mxl.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class StatementDemo{
public static void main(String[] agrs){
Connection connection=null;
Statement statement=null;
try{
String insertSql="insert into tab_user value(1,'admin','admin','王丽丽','女',25)";
String updateSql="update tab_user set realname='王丽'where id=1";
Class.forName("com.mysql.jdbc.Driver");
connection=DriverManager.getConnection(""+"jdbc:mysql://localhost/db_user?useUnicode=ture&&characterEncoding=GBK","root","root");
statement=connection.createStatement();
int num=statement.executeUpdate(insertSql);
if(num>0){
int updateNum=statement.executeUpdate(updateSql);
if(updateNum>0){
System.out.println("向tab_user表添加并修改一条数据!");
}else{
System.out.println("修改失败");
}
}else{
System.out.println("添加失败");
}
}catch(ClassNotFoundException e1){
System.out.println("无法找到驱动类");
}catch(SQLException e2){
System.out.println("执行SQL语句出错");
e2.printStackTrace();
}catch(Exception e3){
System.out.println(e3.getMessage());
}finally{
try{
if(connection!=null&&(!connection.isClosed())){
connection.close();
}
if(statement!=null){
statement.close();
statement=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
运行结果:执行SQL语句出错
java.sql.SQLException: The connection property 'useUnicode' only accepts values of the form: 'true', 'false!'!, 'yes!'! or 'no'. The value 'ture' is not in this set
昨天才装的MySQL,JDBC驱动程序在D:\Program Files\Java\jdk1.8.0_31\jre\lib和D:\Program Files\Java\jdk1.8.0_31\lib都存放有,在Myeclipse上加载了jar驱动包。
求大神告知是否是配置出了问题,还是程序问题?怎么修改?