JAVA 操作遠程mysql數據庫實現單表增刪改查操作


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注釋掉,允許遠程訪問


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM