When you say "sometimes it won't load", does that really mean that sometimes "it does load"? If "sometimes it works" and "sometimes it doesn't", the possible explanations include:
- Sometimes the database connection drops out or fails after you connect. (How stable is your database server and your network connection to it?)
- Sometimes the query result is too large, and because you aren't handling that very well, your script has a problem with memory or cpu usage (or network bandwidth).
- The connection and the query actually do work every time, but because your Tk display logic is pretty bad right now, you can't tell that the query actually worked.
I'm guessing that the third one is most likely what is really going on. Here's a slightly modified version of your script that might get you headed in the right direction:
#!/usr/bin/perl
use strict;
use warnings;
use Tk;
use DBI;
use DBD::mysql;
our $type="mysql";
our $database="store";
our $host="somesite.com";
our $port="3306";
our $tablename="vegetables";
our $user="example";
our $pwd="*********";
our $dsn="dbi:$type:$database:$host:$port";
our $query;
our $queryhandle;
our $connect=DBI->connect($dsn,$user,$pwd) || die "ERROR: $!\n";
my $mw=new MainWindow;
$mw->Label(-text=>"Search for vegetables")->pack; # fix misspelled "L
+able"
my $veges=$mw->Entry()->pack;
$mw->Button(-text=>"Search",-command=>\&search)->pack;
# Declare a variable and just one Label widget for displaying results:
my $result_string;
my $results = $mw->Label( -textvariable => \$result_string )->pack;
sub search{
my $sv=$veges->get();$veges->delete(qw/0 end/);
$query="SELECT count(*) FROM vegetables WHERE vegetable LIKE '%$sv
+%'";
$queryhandle=$connect->prepare($query);
$queryhandle->execute;
my ( $hit_count ) = $queryhandle->fetchrow_array; # there's just o
+ne row
$result_string = sprintf( "Found %d matches for %s", $hit_count, $
+sv );
# assigning a new value to $result_string will update the Labe
+l display
}
MainLoop;
When you want to show an actual list of rows that are returned by a query, try using a Listbox or Text widget, something that can hold all the results in a single scrollable object.
(As posted, your script creates a new Label widget for every row in the query result, so if the first query returns 50 rows, you get 50 Labels stacked vertically that all say the same thing. That's pretty useless - once the window expands to the bottom of the screen, you can see anything else, and those first 50 labels never go away, so you'll never see results from a second or third query.)