Table of Contents
PHP casual notes organized PHP script and JAVA to connect mysql database, javamysql
Home Backend Development PHP Tutorial PHP casual notes organization PHP script and JAVA connect to mysql database, javamysql_PHP tutorial

PHP casual notes organization PHP script and JAVA connect to mysql database, javamysql_PHP tutorial

Jul 12, 2016 am 09:04 AM
java mysql mysql database php database Script

PHP casual notes organized PHP script and JAVA to connect mysql database, javamysql

environment

Development package: appserv-win32-2.5.10

Server: Apache2.2

Database: phpMyAdmin

Language: php5, java

Platform: windows 10

java driver: mysql-connector-java-5.1.37

Demand

Write a PHP script language and connect to the test library of phpMyAdmin database

Write a java web server and connect to the test library of phpMyAdmin database

Code

php connection method

mysql.php

<&#63;php
/*****************************
*数据库连接
*****************************/
$conn = @mysql_connect("localhost","root","123");
if (!$conn){
  die("连接数据库失败:" . mysql_error());
}
mysql_select_db("test", $conn);
//字符转换,读库
mysql_query("set character set utf8");
mysql_query("set names utf8");
&#63;>
Copy after login

test.php test

<&#63;php 
  error_reporting(0);     //防止报错
  include('mysql.php');
  $result=mysql_query("select * from user"); //根据前面的计算出开始的记录和记录数
  // 循环取出记录
  $six;
  while($row=mysql_fetch_row($result))
  {  
  echo $row[0];
  echo $row[1];
  }
&#63;>
Copy after login

Running screenshot:

java connection method

1. Create a new java project as mysqlTest

2. Load JDBC driver, mysql-connector-java-5.1.37

MySQLConnection.java

package com.mysqltest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/*
 * **Mysql连接**
 * 
 * 参数:
 * conn 连接
 * url mysql数据库连接地址
 * user 数据库登陆账号
 * password 数据库登陆密码
 * 方法:
 * conn 获取连接
 */
public class MySQLConnection {
  public static Connection conn = null;
  public static String driver = "com.mysql.jdbc.Driver";
  public static String url = "jdbc:mysql://127.0.0.1:3306/post";
  public static String user = "root";
  public static String password = "123";
  /*
   * 创建Mysql数据连接 第一步:加载驱动 Class.forName(Driver) 第二步:创建连接
   * DriverManager.getConnection(url, user, password);
   */
  public Connection conn() {
    try {
      Class.forName(driver);
    } catch (ClassNotFoundException e) {
      System.out.println("驱动加载错误");
      e.printStackTrace();
    }
    try {
      conn = DriverManager.getConnection(url, user, password);
    } catch (SQLException e) {
      System.out.println("数据库链接错误");
      e.printStackTrace();
    }
    return conn;
  }
}
Copy after login

Work.java

package com.mysqltest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
 * mysql增删改查
 */
public class Work {
  /*
   * insert 增加
   */
  public static int insert() {
    MySQLConnection connection = new MySQLConnection();
    Connection conns; // 获取连接
    PreparedStatement pst; // 执行Sql语句
    int i = 0;
    String sql = "insert into user (username,password) values(&#63;,&#63;)";
    try {
      conns = connection.conn();
      pst = conns.prepareStatement(sql);
      pst.setString(1, "lizi");
      pst.setString(2, "123");
      i = pst.executeUpdate();
      pst.close();
      conns.close();
    } catch (SQLException e) {
      System.out.println("数据写入失败");
      e.printStackTrace();
    }
    return i;
  }
  /*
   * select 写入
   */
  public static void select() {
    MySQLConnection connection = new MySQLConnection();
    Connection conns; // 获取连接
    PreparedStatement pst; // 执行Sql语句(Statement)
    ResultSet rs; // 获取返回结果
    String sql = "select * from user";
    try {
      conns = connection.conn();
      pst = conns.prepareStatement(sql);
      rs = pst.executeQuery(sql);// 执行sql语句
      System.out.println("---------------------------------------");
      System.out.println("名字    |    密码");
      while (rs.next()) {
        System.out.println(rs.getString("username") + "    |    " + rs.getString("password"));
      }
      System.out.println("---------------------------------------");
      conns.close();
      pst.close();
      rs.close();
    } catch (SQLException e) {
      System.out.println("数据查询失败");
      e.printStackTrace();
    }
  }
  /*
   * update 修改
   */
  public static int update() {
    MySQLConnection connection = new MySQLConnection();
    Connection conns; // 获取连接
    PreparedStatement pst; // 执行Sql语句(Statement)
    int i = 0;
    String sql = "update user set password = &#63; where username = &#63;";
    try {
      conns = connection.conn();
      pst = conns.prepareStatement(sql);
      pst.setString(1, "123");
      pst.setString(2, "lizi");
      i = pst.executeUpdate();
      pst.close();
      conns.close();
    } catch (SQLException e) {
      System.out.println("数据修改失败");
      e.printStackTrace();
    }
    return i;
  }
  /*
   * delete 删除
   */
  public static int delete() {
    MySQLConnection connection = new MySQLConnection();
    Connection conns; // 获取连接
    PreparedStatement pst; // 执行Sql语句(Statement)
    int i = 0;
    String sql = "delete from user where username = &#63;";
    try {
      conns = connection.conn();
      pst = conns.prepareStatement(sql);
      pst.setString(1, "lizi");
      i = pst.executeUpdate();
      pst.close();
      conns.close();
    } catch (SQLException e) {
      System.out.println("数据删除失败");
      e.printStackTrace();
    }
    return i;
  }
  /*
   * test
   */
  public static void main(String[] args) {
    // System.out.println(insert());
     select();
    // System.out.println(update());
    // System.out.println(delete());
  }
}

Copy after login

test screenshot

ps: PHP operates statements in the MySQL database

We often use the conn.php file to establish a link with the database, and then use include to call it in the required files. This effectively prevents changes to database attributes from causing errors in data calls from other related files.

Now look at a conn.php file, the code is as follows:

<&#63;php
 $conn=@mysql_connect("localhost","root","")or die("数据库连接错误");//链接数据库服务器
 mysql_select_db("messageboard",$conn);//选择数据库名为messageboard
 mysql_query("set names 'utf'");//使用utf编码,这里不能写成utf-否则将显示乱码,但UTF不区分大小写
 &#63;>
Copy after login

Accumulation of learning and collection of several basic functions for PHP to operate MYSQL:

. Use the mysql_connect() function to connect to the MySQL server: mysql_connect("hostname", "username", "password");
For example, $link = mysql_connect("localhost", "root", "") or die("Cannot connect to the database server! The database server may not be started, or the username and password are incorrect!".mysql_error());

. Use the mysql_select_db() function to select the database file: mysql_query("use database name",$link);

For example, $db_selected=mysql_query("use example",$link);

. Use the mysql_query() function to execute SQL statements: mysql_query(string query(SQL statement),$link);

For example:

Add member: $result=mysql_query("insert into tb_member values('a','')",$link);

Modify member: $result=mysql_query("update tb_member setuser='b',pwd=''where user='a'",$link);

Delete member: $result=mysql_query("delecte from tb_member where user='b'",$link);

Query members: $sql=mysql_query("select * from tb_book");

Fuzzy query: $sql=mysql_query("select * from tb_book where bookname like '%".trim($txt_book)."%'");

//The universal character % represents zero or any more characters.

Display table structure: $result=mysql_query("DESC tb_member");

. Use the mysql_fetch_array() function to obtain information from the array result set:

Syntax structure: array mysql_fetch_array(resource result[,int result_type])

The parameter result resource type is an integer parameter. The data pointer to be passed in is the data pointer returned by the mysql_fetch_array() function;

Parameter result_type: optional, the basic integer parameter for PHP to operate the MySQL database statement. The parameters to be passed in are MYSQL_ASSOC (associative index), MYSQL_NUM (numeric index) MYSQL_BOTH (including the first two, default value)

For example:

<>$sql=mysql_query("select * from tb_book");
$info=mysql_fetch_object($sql);
<>$sql=mysql_query("select * from tb_book where bookname like '%".trim($txt_book)."%'");
$info=mysql_fetch_object($sql);
Copy after login

. Use the mysql_fetch_object() function to get a row from the result set as an object:

Syntax structure: object mysql_fetch_object(resource result);

For example:

<>$sql=mysql_query("select * from tb_book");
$info=mysql_fetch_object($sql);
<>$sql=mysql_query("select * from tb_book where bookname like '%".trim($txt_book)."%'");
$info=mysql_fetch_object($sql);
Copy after login

The mysql_fetch_object() function is similar to the mysql_fetch_array() function, with one difference, that is, it returns an object instead of an array. This function can only access the array through the field name. Syntax structure for accessing row elements in a result set: $row->col_name(column name)

. Use the mysql_fetch_row() function to obtain each record in the result set row by row:

Syntax structure: array mysql_fetch_row(resource result)

For example:

<>$sql=mysql_query("select * from tb_book");
$row=mysql_fetch_row($sql);
<>$sql=mysql_query("select * from tb_book where bookname like '%".trim($txt_book)."%'");
$row=mysql_fetch_row($sql);
Copy after login

. Use the mysql_num_rows() function to obtain the number of records in the result set:

Syntax structure: int mysql_num_rows(resource result)

For example:

$sql=mysql_query("select * from tb_book");
......
<&#63;php $nums=mysql_num_rows($sql);echo $nums;&#63;>
Copy after login

Note: To obtain the data affected by insert, update, and delete statements, you must use the mysql_affected_rows() function.

.mysql_query("set names gb");//Set the encoding format of MySQL to gb type to block garbled characters.

. Close the record set: mysql_free_result($sql);

. Close the MySQL database server: mysql_close($conn);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1075074.htmlTechArticlePHP notes organized by PHP script and JAVA to connect to mysql database, javamysql environment development package: appserv-win32-2.5. 10 Server: Apache2.2 Database: phpMyAdmin Language: php5, java ping...
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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles