JDBC连接数据库——添加

来源:互联网 发布:linux安装软件步骤 编辑:程序博客网 时间:2024/04/24 22:24
/**

 * JDBC连接数据库——添加

 * 小珂

 *2016/6/7

 * */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class Jdbc_add {


public static void main(String[] args) {
Connection conn = null;
ResultSet rs = null;
String username = "admin";
String password = "12333";
// 创建PreparedStatement 对象
PreparedStatement pstm = null;
// URL编写方式:jdbc:mysql:// 主机名称: 连接端口/数据库的名称
String url = "jdbc:mysql://localhost:3306/users?characterEncoding=utf8";
// 驱动
String drive = "com.mysql.jdbc.Driver";
//1.加载MySql的驱动类
try {
Class.forName(drive);
//2.连接数据库
conn = DriverManager.getConnection(url, "root", "123");
//3.创建一个PreparedStatement对象--负责将sql语句发送给数据库
String sql="insert into userinfo(username,password) values (?,?)";
pstm = conn.prepareStatement(sql);
/**增
* 4.设置占位符
* */

pstm.setString(1,"三毛");//直接给占位符赋值
String word="123123";//通过声明变量给占位符赋值
pstm.setString(2,word);
//5.发送SQL语句
int add=pstm.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
// 6.释放资源
finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

}

本人小白一枚,自己学习中的笔记。

1 0