1.先新建一个数据库,代码如下:
CREATE TABLE user_t (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL DEFAULT '',
password VARCHAR(50) NOT NULL DEFAULT '',
email VARCHAR(50) NOT NULL DEFAULT '',
PRIMARY KEY (id)
) ENGINE=INNODB DEFAULT CHARSET=UTF8;
insert into user_t (id,name,password,email) values
('1','tom','123','tom@163.com'),
('2','jack','456','jack@163.com');
2.java代码如下:
package JdbcPrictice;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.Normalizer.Form;
import javax.swing.text.DefaultEditorKit.InsertBreakAction;
import jdk.nashorn.internal.ir.ForNode;
public class MyJdbc {
//方法getConnection() 获取与数据库连接
public static Connection getConnection()
{
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/new_Prictice","root","");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
//往数据库中添加数据的方法
public void insert()
{
Connection con=this.getConnection();
try {
String sql="insert into user_t (id,name,password,email) values "
+ "('3','liuye','admin','liuye@163.com')";
Statement st=con.createStatement();
int count =st.executeUpdate(sql);
System.out.println("数据库添加了"+count+"条记录");
} catch (Exception e) {
e.printStackTrace();
}
}
//更新数据库已有记录的方法
public void update(){
Connection con = this.getConnection();
try {
String sql ="update user_t set email='bwt149@163.com' where name='tom'";
Statement st=con.createStatement();
int count=st.executeUpdate(sql);
System.out.println("想数据库更新了"+count +"条记录");
} catch (Exception e) {
e.printStackTrace();
}
}
//删除已有记录的方法
public void delete(){
Connection con=this.getConnection();
try {
//将sql代码包装到字符串
String sql="delete from user_t where name='tom'";
Statement st=con.createStatement();
// 调用execute方法执行sql语句 st.execute(sql);
//此方法可以再执行sql的同时获取更改的次数
int count =st.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
//执行已有的数据库操作方法
public static void main(String[] args) {
MyJdbc my= new MyJdbc();
//my.insert();
//my.update();
my.delete();
}
/*
此main()方法为查询数据库的方法
public static void main(String[] args) {
String sql="Select*from user_t";
Connection con=null;
Statement st=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库驱动加载成功");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/new_prictice","root","");
System.out.println("数据库连接成功");
st=con.createStatement();
rs=st.executeQuery(sql);
while(rs.next()){
System.out.print(rs.getInt("id")+" ");
System.out.print(rs.getString("name")+" ");
System.out.print(rs.getString("password")+" ");
System.out.print(rs.getString("email")+" ");
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
rs.close();
} catch (Exception e2) {
e2.printStackTrace();
}
try {
st.close();
} catch (Exception e2) {
e2.printStackTrace();
}
try {
con.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}*/
}