import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
import com.mysql.jdbc.Statement;
public class jdbcUpdate {
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
//写法之一
try {
Class.forName("com.mysql.jdbc.Driver");
//java外部包的类名
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:端口号/数据库名称","账号","密码");
//建立数据库链接
Statement st=(Statement) con.createStatement();
String sql="UPDATE friends SET name='hehe'where id=5";
//更改数据的sql语句
// String sql="INSERT INTO friends(name,id) values('wll',10)";
//插入数据,在表friends里插入数据,id=10,name=wll
//String sql="DELETE FROM friends where id=0 or id=1 or id=5";
//删除数据
int rows=st.executeUpdate(sql);
//st.executeUpdate(sql)这句话执行sql语句,并返回执行了多少行
st.close();
con.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//写法之二
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/wll";//含义同上
String user="root";
String pwd="111111";
try {
Class.forName(driver);
Connection con=DriverManager.getConnection(url,user,pwd);
String insert="insert friends(id,name)values(?,?)";
PreparedStatement prestatement=con.prepareStatement(insert);
String [] names={"huhu","hehe","haha"};
for (int i = 0; i < (names.length); i++) {//插入多条数据
prestatement.setInt(1,i);
prestatement.setString(2, names[i]);
prestatement.execute();
}
String query="select *from friends";
ResultSet reslut=prestatement.executeQuery(query);//执行查找语句,并返回结果给reslut
while (reslut.next()) {
System.out.println(reslut.getString("name"));
System.out.println(reslut.getInt("id"));
}
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
其他数据库也差不多,url那块换一下,jar包换一下,这里只有提供mysql的jar包,其他包可以去相应的官网下
顺便给个mysql jar包的链接吧http://download.youkuaiyun.com/detail/a64796187/6261191