mysql与简单的jdbc操作
时间:2021-07-01 10:21:17
帮助过:28人阅读
//法一statement使用
public
static void main(String[] args) {
//先导入驱动的jar包(可以网上下载mysql jdbc 驱动),右键属性-->java build path-->add external jars
String url="jdbc:mysql://localhost:3306/student";
//连接数据库的url地址
String username="root";
//数据库的用户名
String password="123";
//数据库的密码
Connection con=
null;
try
{
//1.加载mysql数据库驱动
Class.forName("com.mysql.jdbc.Driver"
);
//2.建立数据库连接,connection是java.sql包下的
con=
DriverManager.getConnection(url, username,password);
if(con!=
null)
{
System.out.println("数据库连接成功"
);
}else {
System.out.println("数据库连接不成功"
);
}
//3创建sql语句对象
Statement statement=
con.createStatement();
//String sql="insert into login values(‘xiaoge‘,‘female‘,‘shandong‘)";
//String sql="delete from login where name=‘jack‘";
String sql="update login set name=‘lucy‘ where city=‘nanjing‘"
;
//4执行语句
int r=
statement.executeUpdate(sql);
if (r>0
) {
//System.out.println("insert success..");
//System.out.println("update success..");
System.out.println("delete success..."
);
}
else {
//System.out.println(" fail..");
}
}
catch (Exception e)
{
e.printStackTrace();
//如果出错,在命令行打印异常信息在程序中出错的位置及原因。
}
finally
{
//5.释放资源
if (con!=
null) {
try
{
con.close();
con=
null;
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
//法二preparedstatement
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","123");
String sqlString="insert into login values(?,?,?)";
PreparedStatement preparedStatement=connection.prepareStatement(sqlString);
int rSet=preparedStatement.executeUpdate();
//小标为1开始
// preparedStatement.setString(1, "lifang");
// preparedStatement.setString(2, "female");
// preparedStatement.setString(3, "guangdong");
preparedStatement.setString(1, "tom");
preparedStatement.setString(2, "man");
preparedStatement.setString(3,"beijing");
int result=preparedStatement.executeUpdate();
if (result>0) {
System.out.println("insert success..");
}
else {
System.out.println("insert fail..");
}
} catch (Exception e) {
e.printStackTrace();
}
}
mysql与简单的jdbc操作
标签: