package MysqlTest; import java.sql.DriverManager; import java.sql.ResultSet; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.Statement; public class MysqlTest02 { public static void main(String[] args) { //连接url String url = "jdbc:mysql://10.1.1.136:3306/JAVADB"; //连接driver String driver = "com.mysql.jdbc.Driver"; //用户名 String name = "root"; //密码 String pwd = "root"; try{ Class.forName(driver); Connection connection = (Connection) DriverManager.getConnection(url, name, pwd); System.out.println("connection success"); //增添 // String sql ="insert into TEST(name,func) values(?,?)"; // PreparedStatement statement = (PreparedStatement) connection.prepareStatement(sql); // statement.setObject(1,"高文斌"); // statement.setObject(2,"准备找工作"); // int result = statement.executeUpdate(); // if (result == 1){ // System.out.println("插入成功"); // } // connection.commit(); //查询 // String sql1 = "select * from TEST WHERE ID > ?"; // PreparedStatement sta1 = (PreparedStatement) connection.prepareStatement(sql1); // sta1.setInt(1, 1); // ResultSet re = sta1.executeQuery(); // while (re.next()){ // String names = re.getString(2); // String func = re.getString(3); // System.out.println(names+"\t:"+func); // } // System.out.println("查询完毕"); // //删除 // String ddl = "delete from TEST where name = ‘高文斌‘"; // Statement sta = (Statement) connection.createStatement(); // int eff = sta.executeUpdate(ddl); // System.out.println(eff); //更改 Statement s = (Statement) connection.createStatement(); int b = s.executeUpdate("update TEST set name=‘周文王‘ where name=‘李四‘"); System.out.println(b); }catch (Exception e) { System.out.println(e); } } }
准备工作:
1.下载mysql-connector-java-5.1.45.zip包到本地
2.配置好远程数据库配置文件,我的是在虚拟机上模仿的,文件位置在/etc/mysql/mysql.conf.d/mysqld.cnf,找到bind-address = 127.0.0.1注释掉,允许远程访问