java操作mysql

demo


1. 下载java的mysql驱动

mysql-connector-java-5.1.26-bin.jar 下载

2. 导入工程

在工程的树状文件结构里右击以上jar文件选择build path再选择add to build path

3. 代码如下

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
66
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JavaMysqlConnection{
public static void main(String[] args){
//variables used to operate the mysql database
Connection connection = null;
Statement statement = null;
String sql = null;
ResultSet resultSet = null;
//the information of mysql database
String user = "root";
String password = "root";
String url = "jdbc:mysql://localhost/test";
//look up the mysql diriver , is it useful ?
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println("mysql driver is not ready ...");
e.printStackTrace();
}
// open a mysql connection to java application
try{
connection = DriverManager.getConnection(url,user,password);//url,user,password
}catch(SQLException e){
System.out.println("there is sql exception when connecting ...");
e.printStackTrace();
}
// operate the mysql
try{
statement = connection.createStatement();
sql = "select * from test";//sql to execute
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("id:"+resultSet.getInt("id")+"\tname:"+resultSet.getString("name")+"\tage:"+resultSet.getInt("age")+"\tdescription:"+resultSet.getString("description"));
}
}catch(SQLException e){
System.out.println("there is sql exception ...");
e.printStackTrace();
}
// close the connection
try{
if(resultSet!=null){
resultSet.close();
resultSet = null;
}
if(statement!=null){
statement.close();
statement = null;
}
if(connection!=null){
connection.close();
connection = null;
}
}catch(Exception e){
System.out.println("something was wrong when closing the connection to mysql ...");
e.printStackTrace();
}
System.out.println("java connection to mysql is ending...");
}
}

4. insert

1
2
sql = "insert into test(id, name, age, description) values(88,'sofia', 19, 'this is sofia ...')";
statement.executeUpdate(sql);

5. update

1
2
sql = "update test set name='tony' where id>6";
statement.executeUpdate(sql);

6. delete

1
2
sql = "delete from test where name='tony'";
statement.execute(sql);

7. 参考

波纹的博客

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 1. 下载java的mysql驱动
  2. 2. 2. 导入工程
  3. 3. 3. 代码如下
  4. 4. 4. insert
  5. 5. 5. update
  6. 6. 6. delete
  7. 7. 7. 参考
,