jdbc
查询语句使用
select数据库名from表名id=?来查
public static void main(String[]args){
try{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
String username = "root";
Stirng password = "root";
String url = "jdbc:mysql://localhost:3306/kgcnews";
//创建链接
Connection connection = DriverManager.getConnect(usrl,username,password);
//SQL语句
String sql = "select username from news_user where id = ?";
//创建执行者
PreparedStatement preparedStatement = connection.preparedStatement(sql);
//设置参数
preparedStatement.setInt(1,3);
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.print(resultSet.getString(username));
}
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
增加数据
增加的语句是insert into 表名 value(增加的数据)
public static void main(String[]args){
try{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
String username = "root";
Stirng password = "root";
String url = "jdbc:mysql://localhost:3306/kgcnews";
//创建链接
Connection connection = DriverManager.getConnect(usrl,username,password);
//SQL语句
String sql = "insert into news_user value(4,'wangyuling',""12345","123@456")";
//创建执行者
PreparedStatement preparedStatement = connection.preparedStatement(sql);
//设置参数
int i = preparedStatement.executeUpdate();
System.out.print("改变的行数有"+i)
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
修改数据
sql语句使用时update 表名 set 内容=? where id=?;
public static void main(String[]args){
try{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
String username = "root";
Stirng password = "root";
String url = "jdbc:mysql://localhost:3306/kgcnews";
//创建链接
Connection connection = DriverManager.getConnect(usrl,username,password);
//SQL语句
String sql = "update news_user set username=? where id=?";
//创建执行者
PreparedStatement preparedStatement = connection.preparedStatement(sql);
//设置参数
preparedStatement.setString(1,"Hello,world");
preparedStatement.setInt(2,3)
int i = preparedStatement.executeUpdate();
System.out.print("改变的行数有"+i)
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
删除数据
删除数据是
delete from 表名 where id=?
public static void main(String[]args){
try{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
String username = "root";
Stirng password = "root";
String url = "jdbc:mysql://localhost:3306/kgcnews";
//创建链接
Connection connection = DriverManager.getConnect(usrl,username,password);
//SQL语句
String sql = "delete from news_user where id =?";
//创建执行者
PreparedStatement preparedStatement = connection.preparedStatement(sql);
//设置参数
preparedStatement.setInt(1,4)
int i = preparedStatement.executeUpdate();
System.out.print("改变的行数有"+i)
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}