Java有点像C++和Python混合品种,方方面面都有点像。本科的时候玩过Java和Android编程,有点基础,现在出来搬砖要捡回去,写一篇博客预习一下。
我一般学代码的步骤都是:定义,变量计算,流程控制,文件操作,数据库,多线程,网络通信。这次把后面三项总结一下。
拿到电脑先配环境,需要装Java的JDK(jdk-8u301-windows-x64.exe),编译器(ideaIU-2021.2.1.exe),mySQL(mysql-installer-community-8.0.26.0.msi),JDBC(mysql-connector-java-8.0.25.tar.gz)
工程路径文件如图:
注意External Libraries中的mysql-conn...,这个是Java连接mySQL的驱动,导入方法是File---Project Structure---Modules---Dependancies---(+)---JARs or Direc...,选择这个文件就行。
工程一共三个文件:
myJDBC.java:使用Java代码操作mySQL数据库进行增删查改
mySocket.java:使用多线程创建socket服务器和客户端
Main.java:如何使用上面文件模块
Main.java
import java.util.Scanner; import java.util.Vector; class Java_Demo { public void SQL_Demo() { myJDBC mj = new myJDBC("caoyi", "root", "admin123"); if (!mj.connect()) { System.out.println("connect failure!"); return; } else { System.out.println("connect success!"); } //mj.execute("INSERT INTO info (NAME, SEX, TELE, CODE_TYPE) VALUES ('鬼七', '男', '15600009982', 'excel')"); Vector<Vector<String>> res = mj.query("select * from info", new String[]{"NAME", "SEX", "TELE"}, 3); if (!mj.disconnect()) { System.out.println("disconnect failure!"); return; } else { System.out.println("disconnect success!"); } } public void TCP_Demo() { Scanner scan = new Scanner(System.in); mySocket ms = new mySocket(); ms.create_server(); while(true) { System.out.println("y:run n:exit"); String str = scan.nextLine(); if(str.equals("y")){ ms.create_client(); }else{ System.exit(0); } } } } public class Main { public static void main(String[] args) { Java_Demo jd = new Java_Demo(); jd.SQL_Demo(); } }
myJDBC.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; class myJDBC { private String driver; private String url; private String user; private String password; private Connection conn; private Statement state; private ResultSet resultSet; //构造函数 参数[数据库名, mysql用户名, mysql密码] protected myJDBC(String db_name, String user, String password) { this.driver = "com.mysql.jdbc.Driver"; this.url = "jdbc:mysql://localhost:3306/" + db_name; //3306是mysql默认端口 this.user = user; this.password = password; } //连接数据库 public boolean connect() { try { Class.forName(driver); } catch (ClassNotFoundException e) { //need mysql-connector-java-X.X.XX.jar return false; } try { conn = DriverManager.getConnection(url, user, password); if (!conn.isClosed()) { return true; } } catch (SQLException e) { return false; } return true; } //断开数据库 public boolean disconnect() { try{ this.conn.close(); } catch (SQLException e) { return false; } return true; } //执行SQL语句 public int execute(String sql) { //添加条目 "INSERT INTO info (NAME, SEX, TELE, CODE_TYPE) VALUES ('李四', '男', '16759840883', 'python')" //删除条目 "DELETE FROM info WHERE (ID = '2')" //修改条目 "UPDATE info SET CODE_TYPE = 'C++' WHERE (ID = '2')" int stat_id = -1; try { state = conn.createStatement(); stat_id = state.executeUpdate(sql); } catch (SQLException e) { return 0; } return stat_id; } //查询内容 以二维容器的形式输出 public Vector<Vector<String>> query(String sql, String[] labels, int label_num) { Vector query_data = new Vector<Vector<String>>(); try { state = conn.createStatement(); resultSet = state.executeQuery(sql); while(resultSet.next()) { Vector data = new Vector<String>(); for(int i=0;i<label_num;i++) { String label = labels[i]; String value = resultSet.getString(label); data.add(value); } query_data.add(data); } resultSet.close(); } catch (SQLException e) { return query_data; } return query_data; } }
mySocket.java
import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; class server_thread extends Thread { private ServerSocket server; private Socket socket; private int port; private DataInputStream dis; private DataOutputStream dos; public void config(int listen_port) { this.port = listen_port; } public void run() { try { server = new ServerSocket(this.port); System.out.println("waiting connect..."); //服务器循环 一次性连接 while(true) { socket = server.accept(); System.out.println("connecting!"); dis = new DataInputStream(socket.getInputStream()); String recv = dis.readUTF(); System.out.println(recv); socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } class client_thread extends Thread { private String server_ip; private int port; private Socket socket; private DataInputStream dis; private DataOutputStream dos; public void config(String server_ip, int listen_port) { this.server_ip = server_ip; this.port = listen_port; } public void run() { try { socket = new Socket(server_ip, port); dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF("Hello Server, I am Client."); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } public class mySocket { public void print_info() { try { InetAddress ia = InetAddress.getLocalHost(); String local_name = ia.getHostName(); String local_ip = ia.getHostAddress(); System.out.println("HostName: "+local_name); System.out.println("IPAddr: "+local_ip); } catch (UnknownHostException e) { e.printStackTrace(); } } void create_server() { server_thread st = new server_thread(); st.config(8998); st.start(); } void create_client() { client_thread st = new client_thread(); st.config("127.0.0.1", 8998); st.start(); } }