1. 程式人生 > >java連線MYSQL

java連線MYSQL

啟動MySQL服務

net start mysql

如果顯示服務名無效,那就安裝服務,然後再啟動服務

mysqld -install

用root登入MySQL,第一次使用不用密碼

mysql -u root -p

 退出登入

exit

 用Java1.8和connectors/J8.0l連線mysql

Class.forName("com.mysql.cj.jdbc.Driver");
	   
String url = "jdbc:mysql://127.0.0.1:3306/book_manage?
              serverTimezone=UTC&useUnicode=true&
              characterEncoding=utf-8&useSSL=false";

附一個例子

import java.sql.*;

public class Userinfo {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
	    Class.forName("com.mysql.cj.jdbc.Driver");
		String url = "jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false";
		String user="root";
	    String password="root";
		Connection con = DriverManager.getConnection(url,user,password);
		Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
		/*建立表ueserindfo
		 * 
		 * String sql = "create table userinfo("+
						"code	varchar(4) not null,"+	
						"name	varchar(10),"+			
						"password varchar(6),"+	
						"email	 varchar(40),"+
						"primary key(code));";
				
		int count = stmt.executeUpdate(sql);*/
		String sql2 = "select * from userinfo";
		
		ResultSet rset = stmt.executeQuery(sql2);
		while(rset.next()){
			int code = rset.getInt("code");
			String name = rset.getString("name");
			String pass = rset.getString("password");
			String email = rset.getString("email");
			System.out.print("代號:"+code+" ");
			System.out.print("姓名:"+name+"   ");
			System.out.print("密碼:"+pass+" ");
			System.out.println("email:"+email+" ");
			
		}
		/*  插入一個記錄
		 *  String sql3 = "insert into userinfo values('7107','帥哥','223333','
[email protected]
')"; * int count2 = stmt.executeUpdate(sql3); * System.out.println(count2); * */ //關閉資料庫 rset.close(); stmt.close(); con.close(); } }