JDBC就是一种MySQL链接Java的规范
版本信息
- idea 2018.3.3
- maven 3.3.9
1.配置maven的环境变量
2.配置idea的maven
1.maven的home
2.maven的conf下的settings.xml
选中后选取maven下的conf目录下的setting.xml文件
3. 创建maven 工程
pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>`在这里插入代码片`
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
</dependencies>
创建java类:JdbcDemo
public static void main(String[] args) throws Exception {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://nodeone:3306/scott?useUnicode=true&characterEncoding=utf8", "root", "123QWEasd!");
System.out.println(con);
con.close();
}
使用jdbc对数据库进行查询和插入操作
package one;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JdbcDemo {
public static void main(String[] args) throws Exception {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://192.168.202.128:3306/scott?useUnicode=true&characterEncoding=utf8", "root", "123QWEasd!");
//dql
// 对数据库中的dept进行查询操作,指定查询dname列的数据
pstmt=con.prepareStatement("select * from dept");
rs=pstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getString("dname"));
}
// //dml
// 对数据库进行插入操作
// pstmt=con.prepareStatement("insert into dept values (60,'bca','cbd')");
//
// System.out.println(pstmt.executeUpdate());
rs.close();
pstmt.close();
con.close();
System.out.println(con);
con.close();
}
}