Home Database Mysql Tutorial MySQL数据库的连接

MySQL数据库的连接

Jun 07, 2016 pm 03:46 PM
m mysql Install database connect first

首先,安装mySQL 5.1和mysQL connector 5.1(还可以安装Navicat for MySQL 10,Navicat是MySQL的一个图形操作工具,可以快速建立表和数据库) 然后,建立数据库文件teachweb和表score,依次使用如下命令: create databaseteachweb CHARACTER SET gbk; use t

首先,安装mySQL 5.1和mysQL connector 5.1(还可以安装Navicat for MySQL 10,Navicat是MySQL的一个图形操作工具,可以快速建立表和数据库)

然后,建立数据库文件teachweb和表score,依次使用如下命令:

    create database teachweb CHARACTER SET gbk;
    use teachweb;

    CREATE TABLE ‘score` (

     `ID`  varchar(20) NOT NULL COMMENT '学号' ,

     `ScoreUsername`  varchar(20) NULL COMMENT '课程名称' ,

     `Score`  int(5) NULL ,

     PRIMARY KEY (`ID`)

     );

其次,把下面的代码保存在connectTest.java文件中

//connectTest.java

import java.sql.*;
public class connectTest {
 public static void main(String[] args){
  String driver="com.mysql.jdbc.Driver"; //加载mysql驱动
     String url="jdbc:mysql://localhost:3306/teachweb"; //数据库文件为teachweb
     String username="root";  //用户名
     String password="root";  //用户密码
     
     try {
      Class.forName(driver);
      Connection conn=DriverManager.getConnection(url,username,password);
      if(!conn.isClosed())
       System.out.println("Succeeded connecting to the Database");
      Statement statement=conn.createStatement();
      String sql="select * from score"; //查询score表
      ResultSet rs=statement.executeQuery(sql);
      System.out.println("------------------------");
      String name=null;
      while(rs.next()){
       name=rs.getString("ID");
       name=new String(name.getBytes("ISO-8859-1"),"GB2312"); //转换字符编码
       System.out.println(rs.getString("ScoreUsername")+"\t"+name);
      }
      rs.close();
      conn.close();            
  } catch (ClassNotFoundException e) {
   System.out.println("Sorry,can't find the Driver");
   e.printStackTrace();
  }catch(SQLException e){
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }    
    
  
 }
}
最后,点击“开始”--》“运行”--》“cmd”--》输入以下两条命令:

javac connectTest.java

java connectTest.java

或者在MyEclipse8.5中运行connectTest.java

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain database indexing strategies (e.g., B-Tree, Full-text) for a MySQL-backed PHP application. Explain database indexing strategies (e.g., B-Tree, Full-text) for a MySQL-backed PHP application. Aug 13, 2025 pm 02:57 PM

B-TreeindexesarebestformostPHPapplications,astheysupportequalityandrangequeries,sorting,andareidealforcolumnsusedinWHERE,JOIN,orORDERBYclauses;2.Full-Textindexesshouldbeusedfornaturallanguageorbooleansearchesontextfieldslikearticlesorproductdescripti

How to change the GROUP_CONCAT separator in MySQL How to change the GROUP_CONCAT separator in MySQL Aug 22, 2025 am 10:58 AM

You can customize the separator by using the SEPARATOR keyword in the GROUP_CONCAT() function; 1. Use SEPARATOR to specify a custom separator, such as SEPARATOR'; 'The separator can be changed to a semicolon and plus space; 2. Common examples include using the pipe character '|', space'', line break character '\n' or custom string '->' as the separator; 3. Note that the separator must be a string literal or expression, and the result length is limited by the group_concat_max_len variable, which can be adjusted by SETSESSIONgroup_concat_max_len=10000; 4. SEPARATOR is optional

What is the difference between UNION and UNION ALL in MySQL? What is the difference between UNION and UNION ALL in MySQL? Aug 14, 2025 pm 05:25 PM

UNIONremovesduplicateswhileUNIONALLkeepsallrowsincludingduplicates;1.UNIONperformsdeduplicationbysortingandcomparingrows,returningonlyuniqueresults,whichmakesitsloweronlargedatasets;2.UNIONALLincludeseveryrowfromeachquerywithoutcheckingforduplicates,

How to lock tables in MySQL How to lock tables in MySQL Aug 15, 2025 am 04:04 AM

The table can be locked manually using LOCKTABLES. The READ lock allows multiple sessions to read but cannot be written. The WRITE lock provides exclusive read and write permissions for the current session and other sessions cannot read and write. 2. The lock is only for the current connection. Execution of STARTTRANSACTION and other commands will implicitly release the lock. After locking, it can only access the locked table; 3. Only use it in specific scenarios such as MyISAM table maintenance and data backup. InnoDB should give priority to using transaction and row-level locks such as SELECT...FORUPDATE to avoid performance problems; 4. After the operation is completed, UNLOCKTABLES must be explicitly released, otherwise resource blockage may occur.

How to select data from a table in MySQL? How to select data from a table in MySQL? Aug 19, 2025 pm 01:47 PM

To select data from MySQL table, you should use SELECT statement, 1. Use SELECTcolumn1, column2FROMtable_name to obtain the specified column, or use SELECT* to obtain all columns; 2. Use WHERE clause to filter rows, such as SELECTname, ageFROMusersWHEREage>25; 3. Use ORDERBY to sort the results, such as ORDERBYageDESC, representing descending order of age; 4. Use LIMIT to limit the number of rows, such as LIMIT5 to return the first 5 rows, or use LIMIT10OFFSET20 to implement paging; 5. Use AND, OR and parentheses to combine

How to drop a view in MySQL How to drop a view in MySQL Aug 14, 2025 pm 06:16 PM

To delete a view in MySQL, use the DROPVIEW statement; 1. The basic syntax is DROPVIEWview_name; 2. If you are not sure whether the view exists, you can use DROPVIEWIFEXISTSview_name to avoid errors; 3. You can delete multiple views at once through DROPVIEWIFEXISTSview1, view2, view3; the deletion operation only removes the view definition and does not affect the underlying table data, but you need to ensure that no other views or applications rely on the view, otherwise an error may be caused, and the executor must have DROP permissions.

ORA-01017: invalid username/password; logon denied ORA-01017: invalid username/password; logon denied Aug 16, 2025 pm 01:04 PM

When encountering an ORA-01017 error, it means that the login is denied. The main reason is that the user name or password is wrong or the account status is abnormal. 1. First, manually check the user name and password, and note that the upper and lower case and special characters must be wrapped in double quotes; 2. Confirm that the connected service name or SID is correct, and you can connect through tnsping test; 3. Check whether the account is locked or the password expires, and the DBA needs to query the dba_users view to confirm the status; 4. If the account is locked or expired, you need to execute the ALTERUSER command to unlock and reset the password; 5. Note that Oracle11g and above versions are case-sensitive by default, and you need to ensure that the input is accurate. 6. When logging in to special users such as SYS, you should use the assysdba method to ensure the password.

How to use IFNULL() in MySQL? How to use IFNULL() in MySQL? Aug 22, 2025 pm 02:00 PM

IFNULL()inMySQLreturnsthefirstexpressionifitisnotNULL,otherwisereturnsthesecondexpression,makingitidealforreplacingNULLvalueswithdefaults;forexample,IFNULL(middle_name,'N/A')displays'N/A'whenmiddle_nameisNULL,IFNULL(discount,0)ensurescalculationslike

See all articles