bastosCoder
bastosCoder

Reputation: 91

Connect swift to sql server

Swift 3 / Xcode 8.3.3

I have an SQL server running on phpmyadmin and I would like to send an SQL request (like : SELECT * FROM database) directly from my Swift code. I did a lot of research but all of the answer use PHP.

In the end, I would like to transform this Java code into Swift:

try (Connection connection = DriverManager.getConnection(url, username, password)) {
    System.out.println("Database connected!");

    // the mysql insert statement
    String query = "SELECT * FROM dbName";

    Statement st = connection.createStatement();
    st.executeUpdate(query);

} catch (SQLException e) {
    throw new IllegalStateException("Cannot connect the database!", e);
}

Upvotes: 5

Views: 10187

Answers (2)

Sumona Salma
Sumona Salma

Reputation: 137

Though you can use REST API to fetch data from any server, but if your project has the requirement to connect with sql server directly from your swift project then you can use "SQLClient" to connect. You will get solution from here - https://github.com/salmasumona/Call-SP-from-iOS-project-using-SQLClient

Upvotes: 2

Achraf
Achraf

Reputation: 1520

First you must write a web service (PHP, JAVA) to query your database.

Create a php code to handle your ios query

    <?php

// Create connection
$con=mysqli_connect("localhost","username","password","dbname");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}



// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM Locations";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

// Close connections
mysqli_close($con);
?>

Next, you need to host your php code to a webhost 'use www.000webhost.com for example'

Then, get the php code from the webhost 'www.000webhost.com/db.php'

Now in your swift code connect to the database via the link you just created

    @IBAction func sendQuery(_ sender: Any) {


        let url = URL(string: "https://wanagetout1.000webhostapp.com/db_copy.php")!

        var request = URLRequest(url: url)

        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        let postString = "your query"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                // check for fundamental networking error
                print(error!)
                return
            }
}

Upvotes: 2

Related Questions