1.首先在建立一个简单的数据库
2.然后在eclipse中新建一个java project。添加一个新的package,取名叫DBConnect;再添加一个新的类取名为class DBConnect 。
package DBConnect;
import java.sql.*;
public class DBConnect {
public static void main(String[] args){
try{
//调用Class.forName()方法加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
System.out.println("成功加载MySQL驱动!");
}catch(ClassNotFoundException e1){
System.out.println("找不到MySQL驱动!");
e1.printStackTrace();
}
String url="jdbc:mysql://localhost:3306/test"; //JDBC的URL
//调用DriverManager对象的getConnection()方法,获得一个Connection对象
Connection conn;
try {
conn = DriverManager.getConnection(url, "root","lhl");
//创建一个Statement对象
Statement stmt = conn.createStatement(); //创建Statement对象
System.out.print("成功连接到数据库!\n");
//插入操作
// String sqlinsert="INSERT INTO user VALUES('xukunjie','654987')";
// int rs1 = stmt.executeUpdate(sqlinsert);
// System.out.println(rs1+"\n");
//修改操作
String sqlupdate = "update user set password='654321' where name='liuhailong'";
// PreparedStatement pst = conn.prepareStatement(sqlupdate);
// pst.setString(1, "liuhailong");
// pst.setString(2 , "654321");
int rs1 = stmt.executeUpdate(sqlupdate);
//删除操作
String sqldelete = "delete from user where name=?";
PreparedStatement pst = conn.prepareStatement(sqldelete);
pst.setString(1,"xukunjie");
pst.executeUpdate();
String sql = "select * from user"; //要执行的SQL
ResultSet rs = stmt.executeQuery(sql);//创建数据对象
System.out.println("姓名"+"\t\t"+"密码");
while (rs.next()){
System.out.print(rs.getString(1) + "\t");
System.out.print(rs.getString(2) + "\t");
// System.out.print(rs.getInt(3) + "\t");
System.out.println();
}
stmt.close();
conn.close();
} catch (SQLException e){
e.printStackTrace();
}
}
}