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

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)

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

What does 'platform independence' mean in the context of Java? What does 'platform independence' mean in the context of Java? Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Redis: Understanding Its Architecture and Purpose Redis: Understanding Its Architecture and Purpose Apr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

See all articles