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

WBOY
WBOYOriginal
2016-07-12 09:04:10745browse

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;>

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;>

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;
  }
}

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());
  }
}

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;>

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);

. 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);

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);

. 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;>

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:
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