首先引用mysql数据库的jar包文件:右键项目—构建路径—设置构建路径—库—添加外部JAR
我的数据库表及表结构:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` varchar(30) DEFAULT NULL,
`username` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
代码如下:
package test2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author lee
*
*/
public class DB {
public static void main(String[] args) throws ClassNotFoundException, SQLException
{
//导入驱动包
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
String jdbc = "jdbc:mysql://localhost:3306/leetest?characterEncoding=GBK";
//我的数据库信息,用户名:root,密码:123456
Connection conn = null;
conn = DriverManager.getConnection(jdbc, "root", "123456");
Statement state = conn.createStatement();
//增加记录
String insertSql = "insert into user values('2','lance','1234')";
state.executeUpdate(insertSql);
//删除记录
String deleteSql = "delete from user where username='lance'";
state.executeUpdate(deleteSql);
//修改记录
String updateSql = "update user set password='123456' where username='1213'";
state.executeUpdate(updateSql);
//查询记录
String sql = "select * from user";
ResultSet rs = state.executeQuery(sql);
while(rs.next())
{//getString(n)获取第n列的内容,数据库中的列数是从1开始的
System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
}
//查询特定条件时,若想避免sql注入,可用以下方法
String sql2 = "select * from user where id=? and username=?";
PreparedStatement ps = conn.prepareStatement(sql2);
ps.setString(1, "1");
ps.setString(2, "shuai");
ResultSet rs2 = ps.executeQuery();
if(rs2.next())
{
System.out.println("pass:"+rs2.getString(3));
}
conn.close();
}
}