DAY1 MYSQL初级(学过数据库,对本人比较简单,算是复习一下)
DAY2 MYSQL高级
DAY3 JDBC
创建空工程项目
配置jdk版本1.8,对应的编译版本8
创建模块,设置名字和位置
d.导入驱动包,将mysql的驱动包放在模块下的lib目录(随意命名)下,并将该
jar包添加为库文件
//Classforname("com.mvsql.jdbc.Driver");注册驱动MYSQL 5版本之后较高已经不需要
String url="jdbbc:mysql://localhost/db1;
//获取连接
String username ="root";
String password="1234";
Connection conn=DriverManager.getconnection(url,username,password);
//定义sql
String sql="update account set monney = 2000 where id =1;
//执行获取sql 对象 statement
Statement stmt=conn.createStatement();
//执行sql
int count=stmt.executeUpdate(sql);//受影响条数
//处理结果
System.out.println(count);
//释放资源
stmt.close();
conn.close();
事务
try{//开启事务
conn.setAutoCommit(false);
//执行sql
int count1=executeStatement(sql1);
//处理结果
System.out.println(count1);
conn.commit();
}catch(Exception e){
conn.rollback();
e.printStackTrace();
}
执行DDL
String url = "jdbc:mysql:///db1?useSSL=false";
String username = "root";
String password = "1234";
Connection conn =
DriverManager.getConnection(url, username,password);
String sql="select * from account";
Statement stmt=conn.createtatement();
ResultSet rs =stmt.executeQUery(sql);
while(re.next()){
int id=rs.getInt("id");
String name=re.getString("name");
double monney=re.getDouble("monney");
System.out.println(id);
System.out.println(name);
System.out.println(money);
}
rs.close();
conn.close();
stmt.close();
使用PreparedStatement,防止SQL注入
public void testPreparedStatement() throw Exception{
String url="jdbc:mysql://db1?useSSL=false;
String username="root";
String password="1234";
Connection conn=DriverManeger.getConnnection(url,username,password);
// 定义sql
String sql = "select * from tb_user where
username = ? and password = ?";
// 获取pstmt对象
PreparedStatement pstmt =
conn.prepareStatement(sql);
// 设置?的值
pstmt.setString(1,name);
pstmt.setString(2,pwd);
// 执行sql
ResultSet rs = pstmt.executeQuery();
// 判断登录是否成功
if(rs.next()){
System.out.println("登录成功~");
}else{
System.out.println("登录失败~");
}
//7. 释放资源
rs.close();
pstmt.close();
conn.close();
}
}
数据库连接池
public class DruidDemo {
public static void main(String[] args) throws
Exception {
//1.导入jar包
//2.定义配置文件
//3. 加载配置文件
Properties prop = new Properties();
prop.load(new FileInputStream("jdbcdemo/src/druid.properties"));
//4. 获取连接池对象
DataSource dataSource =
DruidDataSourceFactory.createDataSource(prop);
//5. 获取数据库连接 Connection
Connection connection =
dataSource.getConnection();
System.out.println(connection); //获取到了连接
后就可以继续做其他操作了
//System.out.println(System.getProperty("user.dir")
);
}
}
实战练习遇到的问题
插入时错误
> 1366 - Incorrect string value: '\xE4\xB8\x89\xE5\x8F\xAA...' for column 'brand_name' at row 1
解决方法:创建表时设置中文编码,再创建表下面接上一句
ENGINE=INNODB DEFAULT CHARSET=utf8mb4;
解决IDEA报 Cannot resolve symbol问题
解决方法:删除.idea文件,重启项目。
Day4 Maven
创建配置maven项目中出现的问题
Unresolved plugin: 'org.apache.maven.plugins:maven-clean-plugin:2.5'
解决方法:解决方法