Now we'll download the example script from this repo apt-get install git if you don't have git installed. Now install the local dependencies with carton they are in the cpanfile of the repository.
Start SQL Server. We'll start it on port this is where the connect script will connect to. Run the connect script. The second time you run connect. To reset the environment, just:. You can connect via a named DSN also. With the odbcinst -q -s command you can see what DSNs are configured in your system. In the example we're using testdsn. This enables DBI to throw exceptions when there are failures.
That is quite old-school. It is necessary to specify dbi:driver in your DSN variable. Now we will set up a function to handle passing SQL statements to the server and checking that they do not return an error. The function above may not be super-efficient, but I have definitely gotten my use out of all of the error checking, especially with scripts that run continuously.
If you have a script that runs continuously, sometimes the SQL server can fail between loops in the script. When you next pass a SQL statement to the server, it will result in error after error. We need to be able to fetch data from the database, or insert data into the database, but for our example to work first we actually need to create the tables of the database. Then we call the do method of the database handle which will send the SQL statement to the database.
The SQL statement is followed by the word undef. That's actually the place of a hash-reference providing parameters to this specific call, similar to the attributes passed to the connect method, but I think it is rarely used in these statements.
The undef is followed by the actual values that go in place of the the place-holders. As you can see we did not have to put the place-holders in any kind of quotes nor did we have to somehow convert the values.
DBI did it for us. This helps us avoid SQL injection attacks. Even if you meet someone called Bobby Tables.
An SQL statement with some place-holders. As the SELECT statement can return a lot of rows and a lot of values in each row we cannot use a simple call to the do method. Instead, there are several ways to fetch the data. I'll show here two. For both we have 3 steps: prepare the SQL statement, execute the statement with specific data, and fetch the rows.
From these, the prepare statement can be shared by - assuming the queries only differ in the data we pass to them. We create an SQL statement using question marks? Then we call the execute method of the statement handle passing to it values that should be placed instead of the place-holders. The third step is the really interesting one.
0コメント