JDBC演示(一)

JDBC经典代码

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
public class test2 {
public static void main(String[] args) {
//"C:\Users\xiaoguan\Downloads\test\com\mysql\jdbc\Driver.class"
Statement stm=null;
Connection conn=null;
try{
//1.注册驱动
Driver driver =new com.mysql.cj.jdbc.Driver();
DriverManager.registerDriver(driver);
//2.获取连接
String name="root";
//URL=通信协议+ip+端口+内容
String url="jdbc:mysql://10.198.179.163:3306/bjpowernode";
String pw="68963120g";
conn=DriverManager.getConnection(url,name,pw);
System.out.println("数据库为"+conn);
//3.获取数据库对象(专门执行sql语句)
stm=conn.createStatement();
String sql="update dept set dname='xdu',loc='西安' where deptno=50";//不用在最后加分号
//4.执行sql
//专门执行DML语句
//返回值影响数据库中的记录条数
int count=stm.executeUpdate(sql);
System.out.println("count为"+count);

}catch(SQLException e){
e.printStackTrace();
}finally
{
//6.释放资源
//重小到大释放,statement---->connection
try
{
if(stm!=null)
{
stm.close();
}
}
catch(SQLException e)
{
e.printStackTrace();
}
try
{
if(conn!=null)
{
conn.close();
}
}
catch(SQLException e)
{
e.printStackTrace();
}


}

}
}
//5.处理查询结果集这里没有演示