1、安装mysql数据库;
2、创建mysql数据库、表、字段定义;
3、创建java项目,右击属性,添加jar包(mysql-connector-java-5.0.8-bin.jar);
4、写如下操作数据库的代码:
import java.sql.Connection;//java包
import java.sql.DriverManager;import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection {
private String dbDriver="com.mysql.jdbc.Driver";
private String dbUrl="jdbc:mysql://localhost:3306/person";//根据实际情况变化 private String dbUrl= "jdbc:mysql://[ip地址]:[端口号]/[数据库名]" ;
private String dbUser="root";
private String dbPass="123456";
public Connection getConn()
{
Connection conn=null;
try
{
Class.forName(dbDriver);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
try
{
conn = DriverManager.getConnection(dbUrl,dbUser,dbPass);//注意是三个参数
}
catch (SQLException e)
{
e.printStackTrace();
}
return conn;
}
//插入操作
public int insert()
{
int i=0;
String sql="insert into person(ID,name,pass) values(?,?,?)";
Connection cnn=getConn();
try{
PreparedStatement preStmt =cnn.prepareStatement(sql);
preStmt.setInt(1,1);
preStmt.setString(2,"name1");//或者:preStmt.setInt(1,值);
preStmt.setString(3,"pass1");//或者:preStmt.setInt(1,值);
i=preStmt.executeUpdate();
cnn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
return i;//返回影响的行数,1为执行成功
}
//更新操作
public int update()
{
int i=0;
String sql="update person set name=?,pass=? where ID=?";//注意要有where条件
Connection cnn=getConn();
try{
PreparedStatement preStmt =cnn.prepareStatement(sql);
preStmt.setString(1,"lp2");
preStmt.setString(2,"lp2");
preStmt.setInt(3,1);
i=preStmt.executeUpdate();
cnn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
return i;//返回影响的行数,1为执行成功
}
//查找操作
public String select()
{
String sql = "select * from person where ID=1";
Connection cnn = getConn();//此处为通过自己写的方法getConn()获得连接
String returnData="";
try
{
Statement stmt = cnn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
{
//int m1 = rs.getInt(1);//或者为rs.getString(1),根据数据库中列的值类型确定,参数为第一列
String m2 = rs.getString(1);
returnData =m2;
}
cnn.close();
//可以将查找到的值写入类,然后返回相应的对象
}
catch (SQLException e)
{
e.printStackTrace();
}
return returnData;
}
//删除操作
public int delete()
{
String sql = "delete from person where ID=1";
int i=0;
Connection conn = getConn();//此处为通过自己写的方法getConn()获得连接
try
{
Statement stmt = conn.createStatement();
i = stmt.executeUpdate(sql);
conn.close();
}catch (SQLException e)
{
e.printStackTrace();
}
return i;//如果返回的是1,则执行成功;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DBConnection connection = new DBConnection();
int count = connection.delete();
System.out.println(count);
}
}